Ogurchik Ogurchik - 3 months ago 10
Ajax Question

Get value form ajax request and give global variable

Sorry folk, I know that my question asked many guys in different form, but I'm disappointed to find a decision my problem.

function testAjax(){
var result = "";
$.ajax({
type: "POST",
dataType: 'jsonp',
url: "https://api.novaposhta.ua/v2.0/json/",
data: {
"modelName": "Address",
"calledMethod": "getCities",
"methodProperties": {},
"apiKey": "6f94a6391cb5134ee68ddb7924de2a3d"
},
success: function(msg) { result = msg }});
return result;
}
var kor = testAjax();
console.log(kor);


I need to take out
data
from the ajax request and assign this
data
to a global variable. But function
testAjax
returns nothing. I think
testAjax
returns nothing because it's an async request to server and completes later than
return result
.
My question - how do I take out a value from
$.ajax()
and assign this value to a global variable? I tried googling and try decide this problem, but ...

Answer

Yes, your hunch is correct - the function is returning result as an empty string because the success handler is called later when the server response is returned. If you wish to do something specific when the response comes in, do so in the success response handler like so:

...
success: function(msg) {
    // now you have the response so do something with it
    console.log(msg);
}
...
Comments