views:

143

answers:

2

I have been using the jquery form plugin to submi forms on my page and it works great.

But when I try to submit a form that has been loaded using .load it doesn't work.

This is my code:

$(document).ready(function() {                 
  //shows loading screen whilst posting via ajax
  $().ajaxStart($.blockUI).ajaxStop($.unblockUI);

  //post form add_customer ajax
  var options = { 
    target: '#alert',   
  };
  $.ajaxSettings.cache = false;
  $('#add_customer').submit(function() {
    $(this).ajaxSubmit(options);
    return false;
  }); 

  $('#theform').hide().load('form.php', function() {
    $(this).fadeIn();
    return false;
  });
});

What am I missing? can't find a solution anywhere.

A: 

Is the form with an id of 'add_customer` inside of the HTML that's loaded from form.php? If that's the case then the submit method binding you're applying is happening before the element is available. To fix it move your method binding inside of the load callback:

$(document).ready(function() {                 
  //shows loading screen whilst posting via ajax
  $().ajaxStart($.blockUI).ajaxStop($.unblockUI);

  $('#theform').hide().load('form.php', function() {
    //post form add_customer ajax
    var options = { 
      target: '#alert',   
    };
    $.ajaxSettings.cache = false;
    $('#add_customer').submit(function() {
      $(this).ajaxSubmit(options);
      return false;
    }); 

    $(this).fadeIn();
    return false;
  });
});
Cryo
Yes it is inside the HTML loaded. The form.php is loaded before I submit the form. How would i move the method binding inside the load callback?
@user272899 That's what I've done in my code sample above, just use that.
Cryo
A: 

If you have a javascript code in file form.php and fetch it using $.load(), then all the js code will be stripped and you will only get the HTML part.

Use $.get to load the whole page, including the js code.

$.get('form.php',
      {},
      function(data){
        $('#theform').html(data).fadeIn();
      });

Now all js code in form.php will running after it's loaded and added to #theform area.

Donny Kurnia
Excellent. You have made my day, big smile on my face!