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?
Your
.post()runs asynchronously. While it starts to run, the javascript interpreter moves on and runs thealert()statement that is outside thepost()body. Since thepost()is asynchronous, it will almost certainly not be complete by the time thatalert()is called, and thus your statusResult and dataResult variables will likely be undefined. Only the code that runs inside thepost()success callback is guaranteed to run in sequence.You also might try using the variable provided directly by the success callback, rather than assigning it to another variable originally defined outside the
.post()block. So:…instead of dataResult.
Could be a red herring, but worth a try.