</div>
</div>
<div class="grid--cell mb0 mt4">
<a href="/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call" dir="ltr">How do I return the response from an asynchronous call?</a>
<span class="question-originals-answer-count">
(38 answers)
</span>
</div>
<div class="grid--cell mb0 mt8">Closed <span title="2014-02-20 11:58:24Z" class="relativetime">6 years ago</span>.</div>
</div>
</aside>
How can I get imageX show it's value when used outside of $.ajax()?
var imageX;
$.ajax({
type: 'GET',
url: 'php/my1.php',
dataType: 'json',
async: 'false',
success: function(response){
imageX = response[0].studentName,
groupX = response[0].subjectId;
}
});
alert(imageX);
</div>
Change
async: 'false',
to
async: false,
'false' is string which is cast to true by Jquery(JS).
Jquery Ajax Documentation says async accept boolean value.
async (default: true): Type: Boolean By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false.
https://api.jquery.com/jQuery.ajax/
async:false will cause the jQuery.ajax() call to block until it returns. instead of this:
function your ajax_calling_function
call your ajax
callback with results
You need to set async: false
(type Boolean).
If you wrap the false
keyword with ', Javascript consider this is a string
. And jQuery consider the async
property setted as true
Actually set async: false
is a bad approach, quote from this answer:
It is generally a bad idea to make AJAX calls synchronous. DON'T DO IT. I'm serious. I only mention it here for the sake of completeness. Why is it bad do you ask?
JavaScript runs in the UI thread of the browser and any long running process will lock the UI, making it unresponsive. Additionally, there is an upper limit on the execution time for JavaScript and the browser will ask the user whether to continue the execution or not. All of this is really bad user experience. The user won't be able to tell whether everything is working fine or not. Furthermore the effect will be worse for users with a slow connection.
One way is to rewrite your code to:
function getImage() {
var imageX;
$.ajax({
type: 'GET',
url: 'php/my1.php',
dataType: 'json',
success: function(response){
imageX = response[0].studentName,
groupX = response[0].subjectId;
}
});
return imageX;
}
then you can pass it to a variable:
var result = getImage();
and get the data that is returned by the AJAX call like this:
result.success(function (data) {
alert(data);
});