Reputation: 1247
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;
}
);
}
},
Upvotes: 1
Views: 8858
Reputation: 25620
Your trying to do too much with beforeSend
. Your better off doing your getComments ajax call first and having it fire the addComment call. Something like this:
if (typeof commentOpen == "undefined") {
getComments({ commentPage: '', ID: "<?=$_REQUEST["ID"]?>" });
}
function getComments(data){
data = $.extend({action : "getComments"}, data);
$.ajax({
type: 'GET',
url: '_php/ajax.php',
data: data,
success: function(data){
$('#comments > ul').html(data);
addComment({
comment_author: comment_author_val,
comment_content: comment_content_val,
comment_parent_id: comment_parent_id_val,
comment_post_id: "<?=$_REQUEST["ID"]?>"
});
}
});
}
function addComment(data) {
data = $.extend({action : "addComment"}, data);
$.ajax({
type: 'POST',
url: '_php/ajax.php',
dataType: "json",
data: data
});
}
Upvotes: 1
Reputation: 7426
Your data retrieval action in beforeSend
is asynchronous, meaning $.get()
returns immediately and then beforeSend
returns 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 way beforeSend
won't return until the data retrieval completes. To do this, merely add async: false
to your $.get()
parameter object.
Upvotes: 3