Why can't change the value from inside Jquery $.post function (JavaScript)

    |
  • Added:
  • |
  • In: Wordpress

I am trying to get the response from ajax call and save it in another value but wont work this is my code

x='go' $.post("someurl",function(data){ x=data; }) alert(x)//go 

or this jsFiddle

I am looking for a solution for this problem without storing the value in any HTML container

This Question Has 3 Answeres | Orginal Question | Ayman Jitan

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

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); 

$.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).


Search
I am...

Sajjad Hossain

I have five years of experience in web development sector. I love to do amazing projects and share my knowledge with all.

NEED HOSTING?
Are you searching for Good Quality hosting?
You can Try It!
Connect Social With PHPAns
Top