How to return a variable from $ .post () in jQuery? Closing a variable?

I am having trouble passing data received from the $ .post () function for use elsewhere in my code. I want to store data as a variable and use it outside of the post () function. This is my code:

var last_update = function() {
$.post('/--/feed',
{func:'latest', who:$.defaults.login},
function($j){
            _j = JSON.parse($j);    
            alert(_j.text); // This one works    
        });
}
alert(_j.text); // This one doesn't
};

last_update(); //run the function

      

Please, help!

+2


a source to share


4 answers


If you want to access the data value outside of the ajax request callback, you will need to put this code in a function and call it from the success callback.

var last_update = function() {
$.post('/--/feed',
{func:'latest', who:$.defaults.login},
function($j){
            _j = JSON.parse($j);    
            alert(_j.text); // This one works   
            someOtherFunc(_j.text); 
        });
}
};

last_update(); //run the function

function someOtherFunc(val) {
    alert(val)
}

      



This is essentially the same as placing the code in a callback, but can be useful if you have some code that is reused elsewhere.

+1


a source


The $.post()

AJAX call is asynchronous - which means the AJAX request is made out of order of normal program execution, and in your program means the second warning is called before the _j is filled. Execution order:

  • call last_update ()
  • make an ajax request, remember to execute the callback function, but not now
  • calling the second warning (_j.text);
  • when the ajax request returns data, execute the callback function


Move the code that uses the AJAX return data into a function success()

(which is your return function function($j)

here) - that's what the success function is for.

$.post()

- these are aliases calling $.ajax()

- full docs here .

+3


a source


You can make your POST request synchronous and have a global _j variable:

// global!!!
var _j;

$.ajax({
  async: false,
  url: '/--/feed',
  data: { func:'latest', who:$.defaults.login },
  success: function($j) {
    _j = JSON.parse($j);    
    alert(_j.text); // This one works
  }
});

function last_update() {
  if (typeof _j != 'undefined') {
    alert(_j);
  }
}

      

Or, you can just call last_update () from your success callback, thus no longer requiring async:

$.ajax({
  url: '/--/feed',
  data: { func:'latest', who:$.defaults.login },
  success: function($j) {
    _j = JSON.parse($j);    
    alert(_j.text); // This one works
    last_update(_j);
  }
});

function last_update(_j) {
    alert(_j);
}

      

0


a source


Create _j

in the area last_update

.

-1


a source







All Articles