Ajax Call waiting for the response of another Ajax Call? - javascript

I have two ajax call that cannot be done in one call. When the first ajax call starts the second ajax call can start immediately or whenever the user presses a send button. If the second ajax call starts he has to wait for the response of the first ajax call because he needs data from it.
How can I achieve that the second ajax call sends his request only after the first ajax call's response has been arrived?
Is there another way than setTimeout?
Can I register a listener for ajax call 2 on ajax call 1 somehow?
My code would be:
var xhrUploadComplete = false;
// ajax call 1
$.ajax({
url: url,
type: "POST",
data: formdata,
processData: false,
contentType: false,
complete: function(response) {
var returnedResponse = JSON.parse(response.responseText);
xhrUploadComplete = true;
}
});
// ajax call 2
if (xhrUploadComplete) {
$.ajax({
url: url2,
type: "POST",
data: formdata2,
processData: false,
contentType: false,
complete: function(response) {
...
}
});
}
Edit: The second ajax call cannot be posted in done() or complete() of the first call, because it depends on the users choice to send the final form. The purpose of this two step process is to send an image to the server just after the user had inserted it to an input type=file.
Edit: In know that I cannot the the if(..) because this is an async call. I wrote it to make clear what I need to do. I think I need something like a future in Java.

xhrUploadComplete will be set to true asynchronously (in the future, when the request has finished) so your if-condition (that is evaluated right after the request is started) will never be fulfilled. You cannot simply return (or set) a value from an ajax call. Instead, move the code that waits for the results into the handler that would have set/returned the variable:
$.ajax({
url: url,
type: "POST",
data: formdata,
processData: false,
contentType: false,
complete: function(response) {
var returnedResponse = JSON.parse(response.responseText);
$.ajax({
url: url2,
type: "POST",
data: formdata2,
processData: false,
contentType: false,
complete: function(response) {
…
}
});
}
});
With the Promise pattern you can compose those even more elegantly:
$.ajax({
url: url,
type: "POST",
data: formdata,
processData: false,
contentType: false
}).then(function(response) {
var returnedResponse = JSON.parse(response.responseText);
return $.ajax({
url: url2,
type: "POST",
data: formdata2,
processData: false,
contentType: false
});
}).done(function(response) {
// result of the last request
…
}, function(error) {
// either of them failed
});
Maybe you need also need this:
var ajax1 = $.ajax({
url: url, …
}).then(function(response) {
return JSON.parse(response.responseText);
});
$(user).on("decision", function(e) { // whatever :-)
// as soon as ajax1 will be or has already finished
ajax1.then(function(response1) {
// schedule ajax2
return $.ajax({
url: url2, …
})
}).done(function(response) {
// result of the last request
…
}, function(error) {
// either of them failed
});
});

Related

How to show only the last ajax request result

Total up the amount of the ajax request and show the ajax response when it is the last ajax response.
In other words, how to use only the response of last sent ajax request.
var req=0;
function ajaxReq(){
req++; /total up the amount of request/
$.ajax({
url: "result.php",
type: 'GET',
contentType: false,
enctype: 'multipart/form-data',
cache: false,
processData: false,
success: function(response) {
if(req==1){ /show the response when this is the last request/
$("#response-element").html(response);
}
req--; /Subtract when every success ajax response/
}
});
}
I using this on viewing messages detail
if the user clicked few threads before the response show out it will show the previous thread detail before the current selected thread detail shown out
Any better solution would be nice for sharing
You should decrement as soon as you send request.
var req=""; // should be a number
function ajaxReq(){
req++; /total up the amount of request/
$.ajax({
url: "result.php",
type: 'GET',
contentType: false,
enctype: 'multipart/form-data',
cache: false,
processData: false,
beforeSend: function() {
if (req > 1) req -= 1;
},
success: function(response) {
if(req==1){ /show the response when this is the last request/
$("#response-element").html(response);
req -= 1;
}
}
});
}
You are more or less on the right lines. This is the only way you can avoid the callbacks of previous calls. You will have to associate an ID with each request and then check if the ID of the request is the last sent request.
var sentReqCount = 0;
setInterval(function() {
sentReqCount++;
ajaxReq(sentReqCount);
}, 100);
function ajaxReq(thisReqId) {
$.ajax({
url: "result.php",
type: 'GET',
contentType: false,
enctype: 'multipart/form-data',
cache: false,
processData: false,
success: function(response) {
if (thisReqId === sentReqCount) {
$("#response-element").html(response);
}
}
});
}

jQuery ajax in ajax request

We have some code(simplified) that looks like bellow. We run function x which does an ajax call. When the call is done we call a different function recalculateOrderObjects which also does an ajax call. When this one is completed, it should output the data that which is obtained via the second call. However, what actually happens is that only the first ajax call is made and the second is not executed (or at least immediately goes to done) but does show the data obtained from the first call as the data obtained from the second one.
When running only the recalculateOrderObjects function the function does work as expected.
Edit 1
The subscription variable is a global
There are no errors on the console
Also, when I first call recalculateOrderObjects independent the function work when first x is called and after that I call recalculateOrderObjects independently the function will not work and shows the same behaviour as when called from `x.'
Edit 2
I tried the suggestion to use successinstead of doneas well. With the same result. recalucateOrderObjects is called succesfully, thought after one executing x the whole ajax call in recalucateOrderObjects is never requested again but instead thinks that it is succesfully executed.
function recalculateOrderObjects() {
$.ajax({
type: 'post',
url: url + "something",
data: {data: subscription}
})
.done(function (data) {
console.log('Data ' + data);
});
}
function x(){
jQuery.ajax({
type: "get",
dataType: "json",
url: url,
async: false
}).done(function (response) {
recalculateOrderObjects();
}
});}
x();
You can't get success responce by ".done" function.
"success" function gives you responce after ajax load.
Please try below code
function recalculateOrderObjects() {
$.ajax({
type: 'post',
url: url + "something",
data: {data: subscription},
success: function(data) {
console.log('Data ' + data);
}
});
}
function x(){
jQuery.ajax({
type: "get",
dataType: "json",
url: url,
success: function(data) {
recalculateOrderObjects();
}
});
}
x();
OR
function x(){
jQuery.ajax({
type: "get",
dataType: "json",
url: url,
success: function(data) {
$.ajax({
type: 'post',
url: url + "something",
data: {data: subscription},
success: function(data) {
console.log('Data ' + data);
}
});
}
});
}
x();

Passing Ajax GET response after initial Ajax POST call

I am trying to do a second ajax call when initial ajax post is done, the initial call is a Post and the second call is a get type, on the second call I am able to get the values of url file.php but can't use the returned value as a condition condition parameter.
here's a copy of the js:
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
dataType: 'json'
})
.done(function() {
//SOME UI UPDATES ARE HAPPENNG HERE
//SOME OTHER AJAX CALL AFTER INITIAL CALL IS DONE
$.ajax({
url: 'progress.php',
type: 'GET',
data: status,
async:false,
cache:false
})
.done(function(response) {
console.log("success"); // GETS STRING VALUE OF PROGRESS.PHP
if (response == "success") {
//DO SOMETHING ELSE
};
})
.fail(function(response) {
console.log("error");
});
})
.fail(function() {
//console.log("error");
//INITIAL POST ERROR GOES HERE
});
response also contains a new line to the end. Better checking the string contains in this case.
response.indexOf('success') !== -1

$.ajax wait for completion without hanging the UI

Let's say for example, I have the following javascript function that returns a boolean:
function CallWebServiceToUpdateSessionUser(target, user)
{
var dataText = { "jsonUser": JSON.stringify(user) };
$.ajax({
type: "POST",
url: target,
data: JSON.stringify(dataText),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response)
{
return true;
},
failure: function (msg)
{
return false;
}
});
}
and the target function on the server that is being called could take up to... 15 seconds to respond.
How do I guarantee that this function will not exit until after the server call has been completed? Or, how can I guarantee that who ever is calling this function will get a true/false and not an undefined?
NOTE:
I've seen people use async: false but that hangs the UI which I do not want.
See http://api.jquery.com/jQuery.ajax/. You need to do an AJAX request with async: true to your parameters. You will then need to edit your code so the code that executes after a successful request is inside the successful block.

"undefined" for alerting an ajax call response , why?

i am trying to alert the return value captured by the ajax request. The web method it is refering is returning a boolean value of true or false, and when i am trying to access it outside the ajax method it gives a message "undefined" :?
<script type="text/javascript" language="javascript">
$(document).ready(function () {
var authInfo;
$.ajax({
type: "POST",
url: "service.asmx/getAuthInfo",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
authInfo = msg.d;
},
});
alert(authInfo);
});
</script>
why is the alert(authInfo) giving me as "undefined" ?? Please help !
where does this piece of code fit on the above context ?
if(auhthInfo){
$(".ansitem").editable('FetchUpdate.aspx', {
style: 'background-color:inherit;',
type: 'textarea',
indicator: '<img src="spinner.gif">',
event: 'dblclick',
onblur: 'submit',
submitdata: function (value, settings) {
return { orgval: value};
},
});
};
Your "$.ajax()" call is asynchronous, and thus the results are not available until the response is returned from the server.
If you put your "alert()" inside the "success" callback, it should work (if the HTTP transaction works).
EDITED TO HANDLE YOUR NEW CODE:
<script type="text/javascript" language="javascript">
$(document).ready(function () {
var authInfo;
$.ajax({
type: "POST",
url: "service.asmx/getAuthInfo",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// alert(msg.d); // here it will work as it is only called when it succeeds.
MyHanlder(msg);
},
});
// alert(authInfo); // here authinfo has no value as the AJAX call may not have returned.
});
function MyHandler(msg) {
if(msg.d){
$(".ansitem").editable('FetchUpdate.aspx', {
style: 'background-color:inherit;',
type: 'textarea',
indicator: '<img src="spinner.gif">',
event: 'dblclick',
onblur: 'submit',
submitdata: function (value, settings) { return { orgval: value}; },
});
};
}
</script>
The request and the response that you get via ajax calls are asynchronous. I think it is not possible to alert the value that you get in response at the end of ready function because you are not assured that you will be getting your response before the function completes execution.
You are alerting the authInfo variable before the actual ajax call have returned. If you try this:
success:function(msg) {
authInfo = msg.d;
alert(authInfo);
}
I think you will get the correct result.
Because the AJAX call is done asynchronously, the alert does not have the value at the time of execution. If you place the alert inside the success function you should see the appropriate results. I also noticed you have an extra comma in the $.ajax parameters after the success function parameter.
It appears:
alert(authInfo);
Is running immediately when your document is ready.
However, the variable is not being initialized until after the AJAX call completes.
Try moving the alert to:
$.ajax({
type: "POST",
url: "service.asmx/getAuthInfo",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
authInfo = msg.d;
alert(authInfo);
},
});
If you need to do anything more complex with the value, you can try re-factoring the code into another function:
function onSuccess(msg)
{
if(msg.d)
{
window.alert('The value is true!');
}
else
{
window.alert('The value is false!')
}
}
$.ajax({
type: "POST",
url: "service.asmx/getAuthInfo",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: onSuccess,
});

Categories