Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

amitshrestha221's avatar

Variable outside ajax request

I want the result of ajax outside the ajax function. My code is below :


    var result;
        
        $.ajax({
            type: "GET",
            url: append_url,
            datatype: "json",
            success: function(data){
                result = data;
                alert(result);                
            }
        });

        
        alert(result);  // outputs undefined


0 likes
6 replies
abaklanov's avatar

The last alert is not able to output result variable because $.ajax() is asynchronous and the moment result is been alerted outside it, this variable is not defined yet.

jimmck's avatar

Just initialize result.

var result = 'Waiting for result...';

abaklanov's avatar
Level 2

To operate result variable outside the ajax request you can set additional param async to $.ajax()

var result;

$.ajax({
  type: "GET",
  url: append_url,
  datatype: "json",
  async: false,
  success: function(data){
    result = data;
    console.log("Inside ajax: "+result);                
  }
});

console.log("Outside ajax: "+result);  // fires only after the ajax request is completed
       

But it's really a bad practice to prevent asynchronous code in js.

What I'd suggest is to work with result inside the callback you assign to success property. That's the right way. To avoid making it a mess, just put callback into a function:

function myCallback(response) {
  result = response;
  console.log("Inside ajax: "+result);                
  // Do whatever you need with result variable
}

$.ajax({
  type: "GET",
  url: append_url,
  datatype: "json",
  success: myCallback,
});

To avoid 'callback hell' in case you're going to make more asynchronous things inside other asynchronous ones, use should utilize Promises to organize code and make it more readable as it'll look like synchronous.

6 likes
Galago's avatar

Like @abaklanov says. You can disable the Ajax request to be asynchronous with adding the following property to your Ajax request:

'''Javascript async: false, '''

Your Ajax request looks like this then:

$.ajax({
    async: false,
        type: "GET",
        url: append_url,
        datatype: "json",
        success: function(data){
            result = data;
                alert(result);                
        }
});

Asynchronous means that other methods (like your alert function) can be called before the Ajax request is completed, so the you alert a variable which isn't filled with data yet). When setting Asynchronous to false, the ajax request has to be finished before other functions can be called, so alert will be invoked after the request is complete and after "result" is filled with data.

insidero's avatar
var array = [1,2,3,4,5,6];

$.each(array,function(i,value){ 

  $.ajax({
    url: "<URL>",
    method: "POST", 
    data: { id: value },
    dataType: "html",
    beforeSend:function( jqXHR ){
      jqXHR.id = value;
    }
  }).done(function( msg, textStatus, jqXHR ) {
     console.log('Request Completed: '+ jqXHR.id);
  }).fail(function( jqXHR, textStatus ) {
     console.log( "Request failed: " + jqXHR.id );
  });

  console.log('First Load. Update Request later!');

});

It will be helpful on multiple request with callback to know which one is complete.

1 like

Please or to participate in this conversation.