Has anyone had the same experiences with jQuery AJAX and the beforeSend property? Any advice how to fix this problem?
What I am doing is reading from a database with an AJAX call before I want to send the new data to the database via AJAX (I need to get to the last page of all comments). What happens is that beforeSend retrieves the data WITH the data which should be sent afterwards. Any ideas?
$.ajax({
type: 'POST',
url: '_php/ajax.php',
dataType:"json",
async:false,
data:{
action : "addComment",
comment_author : comment_author_val,
comment_content : comment_content_val,
comment_parent_id : comment_parent_id_val,
comment_post_id : "<?=$_REQUEST["ID"]?>"
},
beforeSend: function() {
//WHAT A MESS...
if (typeof commentOpen == "undefined") {
$.get("_php/ajax.php", { action: "getComments", commentPage: '', ID: "<?=$_REQUEST["ID"]?>" },
function(data){
$('#comments > ul').html(data);
return true;
}
);
}
},
Your data retrieval action in
beforeSendis asynchronous, meaning$.get()returns immediately and thenbeforeSendreturns immediately. Then the$.ajax()continues execution. At this point, the$.ajax()call is already well underway and has a headstart over the$.get()call. I’m not sure exactly how the two requests are handled concurrently under the covers, but that is the gist of it.What you want to do is have
$.get()execute synchronously, not asynchonously. That waybeforeSendwon’t return until the data retrieval completes. To do this, merely addasync: falseto your$.get()parameter object.