I know this question hast probably been asked a thousand times, but i cannot seem to find the answer. I want result
to be the data returned from the ajax-request, which should be a json-data array (the result of console.log(data)
).
var result = $.ajax({
type: 'GET',
url: dataPath,
dataType: 'json',
success: function(data) {
console.log(data)
},
error: function(){
//alert("damn");
},
data: {},
aync: false
});
console.log(result);
However, console.log(result);
will return some strange object, which I don't know how to handle. Why isn't result
= data
?
First of all remove the
aync: false
from your code. It should be spelledasync: false
but you don't need it to achieve your goal and what it actually does is block the entire browser's user interface resulting in a terrible user experience. Remember that "A" in AJAX means Asynchronous.The result of an
$.ajax()
call is a promise which is not the same as your data, but it can still be useful to get to your data. You just need to use it in a certain way.Try changing:
to:
or:
or even this might work - untested:
See this answer for a better explanation.
There is a small spelling mistake aync: false should read async: false assuming of course that you require the request to run synchronously i.e. for the remainder of your code to wait for this result.
I think that the main issue here is that the result you are trying to output to the console is not being referenced by the ajax request.
It is entirely your choice how you reference the data returned by the ajax request, you chose the word data this could just as easily have been result or json_Data or return_Data or ....
Hence to send the result of the ajax request to the console I would suggest:
You mentioned
console.log(result)
returns a strange object, actually this strange object is known asxhr (XMLHttpRequest)
object.Since the call is
syncronous
because ofasync: false
so it's easy to get thereturned data
likeAs because
result.responseText
will be available only after the request completes and there is no chance to execute thisconsole.log(result.responseText);
because ofasync:false
, before therequest
completes because asyncronous
ajax request hangs on everything before it finish the request.In your
success
callbackdata
will be an object because ofdataType: 'json'
but outside ofsuccess
callback, i.e.console.log(result.responseText);
will be only text so to use it as an object you have to convert it to an object using$.parseJSON(result.responseText)
.Typo.
Change this:
to:
And the
ajax
method still returns the jqXHR object doing the request, not the result. Use thedata
parameter in thesuccess
call and store it somewhere.Initialize
result
insidesuccess
function.