Ogurchik
Ogurchik

Reputation: 75

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 ...

Upvotes: 2

Views: 158

Answers (2)

Abdelrhman Hussien
Abdelrhman Hussien

Reputation: 374

most of the time the logic go inside the success function, whatever you will do with the response do it inside the success function.I think you may bay more time for the code structure and the flow of data inside your app. good luck

Upvotes: 0

stevenelberger
stevenelberger

Reputation: 1368

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);
}
...

Upvotes: 1

Related Questions