Question

I am trying to use JQuery to submit a form without reloading the page. Although this works well with the jQuery Form Plugin on a standalone page I need it to work on a page I've loaded with AJAX.

<script type="text/javascript"> 
  $('#LoadForm').click(function() {
    $('#formDiv1').load('FormGen.asp');
  });
</script>

When I click submit on the loaded form however, the form submits and refreshes the page instead of submitting with just AJAX.

<script type="text/javascript"> 
 // wait for the DOM to be loaded 
 $(document).ready(function() { 
   // bind 'myForm' and provide a simple callback function 
   $('#myForm').ajaxForm(function() { 
      alert("Thank you for your comment!"); 
   }); 
 }); 
</script> 

If I put the code in the page I call and use that standalone it works perfect. It doesn't however work when I am attempting to load the form from another page.

Was it helpful?

Solution

You need to use the on() method to bind to things being loaded by AJAX - http://api.jquery.com/on/

OTHER TIPS

When your page load, the element #myForm does not exist yet in the page (because you load with ajax) so the ajaxForm() plugin is not initialized.

You should initialize it when your ajax content has successfully loaded. To do so, use the callback parameter of the .load() method that is executed when the loading has occurred:

$('#formDiv1').load('FormGen.asp', function(data, status, xhr) {

    // this is executed when the load has finished
    $('#myForm').ajaxForm(function() { 
        alert("Thank you for your comment!"); 
    }); 

});

UPDATE:

eerrrr... my bad, didn't correctly read the quesion - Didier Ghys's answer seems more appropriate.


click() binds an event handler to the "click" JavaScript event. The binding is done when the script is executed.

Since you laod tour form by ajax, I suppose the click() function is called before the form is loaded, and thus there is no binding.

Try using the live() function :

  $('#LoadForm').live("click", function() {
     $('#formDiv1').load('FormGen.asp');
  });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top