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


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.


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.


    //use your data here

or define a function outside

var myFunction = function (data){
  //do stuff with data


$.post is asynchronous - the callback will be executed later, after your alert(x) line.



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

Meet with owner

Sajjad Hossain

Hey, I am Sajjad, working in web development sector since 2012. I love to do amazing things. Let's do a project together.
Connect Social With PHPAns