0

Suppose I'm performing a post request using Jquery:

var information;

$.post( url, function( data ) {
  information = data;
});

console.log(information);//This is undefined! Why?

Why would the information variable be undefined? What should I do to make it store the data even after the post request is over?

idude
  • 4,654
  • 8
  • 35
  • 49
  • Have you checked that `data` is not `undefined` ? – Quannt Nov 08 '15 at 03:46
  • @Quannt Yes, data does have a value – idude Nov 08 '15 at 03:47
  • The post request is not "over", Ajax is asynchronous. That's why it has callback functions, that execute when it is over. – James Nov 08 '15 at 03:51
  • Does this answer your question? [Persist variables between page loads](https://stackoverflow.com/questions/29986657/persist-variables-between-page-loads) – Liam Mar 25 '22 at 08:34

3 Answers3

2

$.post is async so you'll have to use $.ajaxSetup({async:false}); before it to get the result you're expecting.

Basically what's happening is your console.log is running before the $.post callback can save the data into the variable hence the undefined error.

Tim Sheehan
  • 3,994
  • 1
  • 15
  • 18
1

You have to get it from an appropriate callback. The $.post() is asynchronous. Here is an example:

// Get some values from elements on the page:
var $form = $( this ),
  term = $form.find( "input[name='s']" ).val(),
  url = $form.attr( "action" );

// Send the data using post
var posting = $.post( url, { s: term } );

// Put the results in a div
posting.done(function( data ) {
  var content = $( data ).find( "#content" );
  $( "#result" ).empty().append( content );
});

From jQuery documentation here: http://api.jquery.com/jquery.post/

Also, I wouldn't recommend Dontfeedthecode's suggestion. Synchronous mode should never be used in javascript because it has unintended effects like locking up parts of the user interface. It might be OK for testing or particular circumstances, but I thought I should mention this disclaimer.

Dale Gardner
  • 26
  • 1
  • 4
0

$.post is a asynchronous function so at the time you call console.log(information); the information variable still empty, so you should use the data only inside the $.post function or use a call back function.

var information;

$.post( url, function( data ) {
  workDone(data);
});
function workDone(data){
     information = data;
     console.log(information);
}
Alan Rezende
  • 348
  • 2
  • 11