Search code examples
jqueryajaxloadajaxform

jQuery - Post Form Loaded from another page using AJAX


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.


Solution

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