2

I get a response from the POST method. Inside I see the value, but after the POST method returns an empty value. Why, hot fix this?

sample:

$.post('/news/add/', {parent: name, title: 'none'}, function(data){ 
 new_id = data;
 alert(new_id); //11
});
alert(new_id); //empty
Marek Sebera
  • 39,650
  • 37
  • 158
  • 244
lolalola
  • 3,773
  • 20
  • 60
  • 96
  • 5
    Because of the asynchronous nature of an AJAX call. – Pekka Sep 15 '11 at 09:21
  • Where is new_id declared? Or are you not declaring it with `var`? – StuperUser Sep 15 '11 at 09:22
  • possible duplicate of [Why is my JavaScript function not populating my array?](http://stackoverflow.com/questions/7377970/why-is-my-javascript-function-not-populating-my-array) – Pekka Sep 15 '11 at 09:22

2 Answers2

5

Because you are making an asynchronous call the code is run in this order:

1 - $.post('/news/add/', {parent: name, title: 'none'}, function(data){ 
   3 - new_id = data;
   4 - alert(new_id); //11
});
2 - alert(new_id); //empty

You can only use the value returned by your post inside the callback function.

The only other way to do this is to make the request synchronous. But that's really not advised as it can lock out the browser waiting for the response.

Richard Dalton
  • 35,513
  • 6
  • 73
  • 91
1

You maybe want to use the .complete or .success methods: http://api.jquery.com/jQuery.post/#jqxhr-object

duncan
  • 31,401
  • 13
  • 78
  • 99