Why is post() not updating the DOM after it returns? Wierd timing problem observed.

Posted by Sephrial on Stack Overflow See other posts from Stack Overflow or by Sephrial
Published on 2010-05-20T19:53:48Z Indexed on 2010/05/20 20:30 UTC
Read the original article Hit count: 146

Hi all,

I have the following code that is really bugging me, I'm thinking perhaps the post() function needs to be blocking. I am new to jQuery(latest version) and AJAX, but I'm using ColdFusion which returns some HTML in the data variable.

var dataResult;
var statusResult;
$.post('fh_result.cfm',$('#myform').serialize(),function(data,status){
     dataResult = data;
     statusResult = status;
});
//alert(statusResult);
if ('success' == statusResult)
{
    alert(statusResult);
    $('#result').html(dataResult);
}

When I uncomment out the first alert, it returns 'undefined' but then it goes into the if block and the next alert box it says 'success'. If I comment out that line it doesn't make it into the if statement at all. My guess is that I want to make this a blocking call or something because I want to insert the data on the page after the post. I also have a problem when I re-write the top code as follows:

var dataResult;
var statusResult;
$.post('fh_result.cfm',$('#myform').serialize(),function(data,status){
     dataResult = data;
     statusResult = status;

     alert(statusResult);
     $('#result').html(dataResult);
});
//alert(statusResult);

Now in this case, the alert says 'success' when I comment out the second alert box. When I uncomment it out, I get one alert that says success and the other that says undefined, but this time it updates the DOM with the result of the postback as desired. How can I do this without the alert box?

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about javascript-events