Hello. I can not understand what the snag is. I am writing a simple function, as in the example below:

function setCookie(val) { var arr = new Object(); $.ajax({ type: 'post', dataType: 'json', url: 'index.php', data: { val: val, query: 'set-cookie' }, success: function(data) { // тут возвращается, как и должно, число и без массивов: 100 console.log(data); // заношу в объект число, которое пришло с запроса arr = { 'data': data }; } }); // в итоге мне возвращается: Object {} undefined console.log(arr, arr['data']); return arr; } 

The value is lost when inserted into the object. How to bring in the object that came from the request? It seems at the top created the desired global variable, and no result.

Reported as a duplicate by Grundy , user194374, pavel , aleksandr barakin , user207618 members on Aug 14 '16 at 12:14 pm.

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

    2 answers 2

    So nothing will come of it.
    The code is asynchronous, that is, it is executed not immediately, but ... sometime in the future.
    For this you can use the Promise :

     function setCookie(val) { return new Promise((resolve, reject) => { // Оборачиваем код в обещание $.ajax({ type: 'post', dataType: 'json', url: 'index.php', data: { val: val, query: 'set-cookie' }, success: function(data) { // тут возвращается, как и должно, число и без массивов: 100 console.log(data); resolve({ 'data': data }); } }); }); } setCookie(value).then(res => { console.info(res); // { 'data': 100 } }); 

    But it’s more like a crutch (working, but a crutch), it seems like in ES2017 promise Async/Await - this is better.

    • Thank you, I'll see what happens tomorrow. - J. Doe
    • That's just for the full use of the Promise and the arrow functions, the author of the question will have to connect a polyfill and translate the code using babel . Although to solve the problem, it is enough to return from the setCookie function the result of executing the $.ajax(...) command, to which in the external environment you can also assign a handler using .then api.jquery.com/deferred.then - Konstantin Basharkevich
    • @Konstantin Basharkevich, jQuery has its own promise implementation, so no polyfills are needed in this case, as well as the explicit use of native promises - Grundy
    • @Grundy so I’m talking about her =) - Konstantin Basharkevich
    • Tell me how to call it with your values, something I can not. Option, setCookie.then ('...'); does not work. - J. Doe

    It seems that the code is asynchronous and there is nothing really recorded in the variable, but you can make a synchronous request by adding

    async: false,

    after

    url: 'index.php',

    but then the tab at the time of the request will be " blocked " and any code will not be executed until the request is completed , it is better to write asynchronous code but it is harder to write.

    • Thank you, I'll see what happens tomorrow. - J. Doe