What's not a legacy way to make a synchronous ajax call using jQuery?

I have a small javascript function that is just for calling a script to get some data from the database so that it can be used by other client side functions.

I'm using a jQuery call to get the data, but in order to pass an object from the success function scope, I need to disable asynchronous mode, which triggers a failure warning.

My function works as intended, but I would like to use a method that is not deprecated. Here is my function:

function getData(ID) {
  var Data = {};
  $.ajax({
    url: 'script',
    method: 'POST',
    dataType: 'json',
    async: false,
    data: {action: 'get', id: ID },
    success: function(response) {
      Data = response;
    })
  });
  return Data;
}

      

I have changed the variable names for immunity reasons, so I apologize if they are vague.

Also why are synchronous calls considered harmful to end users?

+3


source to share


1 answer


As an AJAX call asynchronous

, you will always receive an empty object ( {}

) in response.

There are 2 approaches.



  • You can do async:false

  • To get the response returned in the AJAX call, try the code below. Who are waiting for a response from the server.

function getData(ID) {
  return $.ajax({
    url: 'script',
    method: 'POST',
    dataType: 'json',
    //async: true,  //default async call
    data: {action: 'get', id: ID },
    success: function(response) {
         //Data = response;
    })
  });
}


$.when(getData(YOUR_ID)).done(function(response){
    //access response data here
});

      

+2


source







All Articles