JQuery return data

So, I have this function:

function getAreas(){
      $.post("/custom_html/weathermap.php",'',
            function(data){

                return data

            }, "json");


}

which works great. now I'm trying to pass data back to a variable, in other words:

var data=getAreas()

but it returns nothing. is there any way to make this work?

Thanx for any help.

+3
source share
4 answers

This is an asynchronous call, so you cannot return from it like that.

You will need to move the code that does something with datato the callback ( function(data){}) function .

function getAreas(){
      $.post("/custom_html/weathermap.php",'',
            function(data){

                //do something with data here, such as calling another function

            }, "json");
}

, . , , , . , , . $.post weathermap.php, . . , - .

- ascii:

       V
       |
User clicks button
(or something else happens)
       |
       |
Your JavaScript runs   
       |
       |
And eventually gets
to the ajax call     -------> SERVER ------>     Server sends data back
                                                           |
                                                           |
                                                 And your callback is run
                                                 on the data and execution
                                                 continues from here
                                                           |
                                                           |
                                                           V
+13

, async false

jQuery.loadView = function(url,data){
    var idata;
    $.ajax({
      type: 'POST',
      url: url,
      data: data,
      dataType: 'html',
      async: false,
      success: function(result){idata = result;}
    });
    return idata;
}
+6

- , - , getAreas() . , return .

To get this working, you need to separate your code from what should happen before you call getAreas () and what happens afterwards.

Then you can get something like:

function getAreas(){ $.post("/custom_html/weathermap.php",'', onGetAreasComplete, "json");
}

function onGetAreasComplete(data)
{
    // do whatever you need to do with data
}


// do whatever you need to do before getAreas()

getAreas();

Hope this makes sense.

+2
source

try it

function getAreas(){
    var ret;
    $.post("/custom_html/weathermap.php",'', function(data){

            ret = data;

        }, "json");

    return ret;
}
-3
source

Source: https://habr.com/ru/post/1761307/


All Articles