Why Can't Change The Value From Inside Jquery $.post Function (javascript)
Solution 1:
$.post
is asynchronous - the callback will be executed later, after your alert(x)
line.
Try:
$.post("someurl",function(data){
x=data;
alert(x)
})
(No, there's no other way around this - you'll have to restructure your code accordingly. Don't be tempted to try setting async
to false
, or you'll end up with bigger problems).
Solution 2:
In Javascript when you make this ajax call you are sending an Asynchronous call to the "someurl". This means your function continues and x remains undefined.
Solutions:
$.post("someurl",function(data){
//use your data here
});
or define a function outside
var myFunction = function (data){
//do stuff with data
}
$.post("someurl",myFunction);
Solution 3:
why first declare x as a string and then put data in the same x? I think you should use json and have your php file parse it into json before sending back. Otherwise it just wont give a response. It will on check whether it has executed the call and that will always be "true" regardless of its succes.
Hope this helps.
BIEG
Post a Comment for "Why Can't Change The Value From Inside Jquery $.post Function (javascript)"