0

I am try to get the json response from a url. Below is the php code which I am requesting to:

if($_POST){
header('Content-type: application/json');
echo '{"hello":"world"}';
}

Below is the javascript I wrote:

$('#site').change(function(){

var result;

$.ajax({
    url: "URL",
    data: { param:value },
    type: "POST",
    dataType: "json",
    success: function(data,textStatus,jqXHR) {

     alert(data['hello']); //output: world
     result = data;

    },

});

    alert(result['hello']); //output: nothing (didn't alert) 
    alert(result); //output: undefined

});

So, my question is how can I assign the data to the result? Thanks.

Edit: My question is duplicated with How to return the response from an AJAX call?

Community
  • 1
  • 1
Newbie
  • 2,775
  • 6
  • 33
  • 40

2 Answers2

2

Put async: false in the ajax attribute

$.ajax({
url: "URL",
data: { param:value },
type: "POST",
dataType: "json",
async: false,
success: function(data,textStatus,jqXHR) {

 alert(data['hello']); //output: world
 result = data;

},

});
Manu M
  • 1,074
  • 5
  • 17
0

While you can get what you want to work by setting the async parameter to false on the AJAX request, I would urge you to embrace the asynchronous nature of AJAX and simply do your work in the success callback.

It's the asynchronous nature of the AJAX call that results (or rather doesn't) in the behavior you observe. The flow of control continues past the call before the request returns it's data. That is code after the AJAX call continues to be executed, it doesn't wait until the request has completed. You can force it to do that by setting async to false, but that will also cause all code executing in the browser to stop until the request returns as well. That defeats the purpose of making the AJAX request in the first place.

Rather, you should get used to using callbacks or deferred.done to schedule work after the completion of the request, embracing it's asynchronous nature. It will take some adjustments to stop thinking procedurally, but it's worth the effort.

tvanfosson
  • 524,688
  • 99
  • 697
  • 795