Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a non-deprecated way of doing a synchronous ajax call using jQuery?

I've got a small javascript function that's only purpose is to call a script to get some data from the database so it can be used by other functions on the client side.

I'm using a jQuery call to get the data but for me to pass the object out of the success functions scope I need to turn asynchronous off which raises a deprecation warning.

My function works as intended currently but I'd like to use a method that isn't 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've changed the variable names for privacy reasons so apologies if they're vague.

Also why is synchronous calls considered harmful to the end users experience?

like image 464
Fashim Avatar asked Jun 20 '17 04:06

Fashim


1 Answers

As AJAX call is asynchronous, you will always get blank object ({}) in response.

There are 2 approach.

  1. You can do async:false
  2. To get response returned in AJAX call try like below code. Which wait for response from 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
});
like image 135
Parixit Avatar answered Oct 12 '22 17:10

Parixit