views:

60

answers:

2

I have a jQuery ajax function. the callback function consists of two functions:

1) Take the ajax result (which is an html form) and insert it as an html span's inner html. 2) Submit this form

How can I ensure that the form is loaded before JavaScript tries to submit it?

Code:

$("select").live("change", function(){
  FormUpdate();
})

function FormUpdate() {

  $.ajax({
  type: "POST",
  url: "index.php?UpdateForm=Yes",
  data: $("#Form").serialize(),
  success: function(msg){
    $("span#Content").html(msg);
    $("#Form").submit();
  }
  });

}

My problem comes because javascript tries to submit the form before it has loaded and my data submitted.

A: 

DOM manipulations are synchronous so the form wont be submitted until afterwards. Are you having a specific problem with this scenario? Please post tons of code, if so :)

thenduks
right, if you can't see it happening (it would be lightening fast :P), you can try putting $('#Form').submit() call in a timeout() function
Nakul
+1  A: 

Just simply put the function for taking ajax result and insert into the DOM in front and the form submission function at the back.

Only after insertion is done, the next function will be called.

Example:

$.ajax({
   type: "POST",
   url: "backend.php",
   data: "name=John",
   dataType: "json"
   success: function(msg){
     $("#thediv").html(msg.html);
     $("form#theform").submit();
   }
 });
thephpdeveloper
I guess I have another issue with my code if the callback function will be synchronous
Brian
what's the issue?
thephpdeveloper