Home > Software engineering >  get ajax return from function
get ajax return from function

Time:06-04

Trying to retrieve ajax data to a variable in jquery from an ajax call with a when call. But the data is as I understand not completed ajax data. Gives response in object form below where I can't access the data under responseJSON.

{readyState: 1, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function, …}

//jQuery code calling the function with ajax

jQuery(document).ready(function() {
  var response = ajaxcall(); 
   console.log(response);
});

//function

function ajaxcall(){
   return $.ajax({
        url: "url",
        type: "POST",
        data: form_data,
        dataType: 'json',
        contentType: false,
        cache: false,
        processData:false,
        beforeSend : function()
        {
        },
        success: function(data)
        {
            if(data=='invalid')
            {
                alert("invalid data");
            }
            else
            {
            // success
                return data;
            }
        },
        error: function(e) 
        {
        }          
    });

}

CodePudding user response:

Yes because ajax call is asychronous. So you have to pass a callback function or use promise or use jquery.when

1.Use $.when

$(document).ready(function() {
  $.when(ajaxcall()).then(response=>{
    console.log(response)
  })
});
function ajaxcall(callback){
  return $.ajax({
      url: "https://jsonplaceholder.typicode.com/users/1",
      type: "GET",
      dataType: 'json'
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

2. Pass callback function as parameter of ajaxCall

$(document).ready(function() {
  var response = ajaxcall((response)=>{
   console.log(response);
  }); 

});
function ajaxcall(callback){
 $.ajax({
    url: "https://jsonplaceholder.typicode.com/users/1",
    type: "GET",
    dataType: 'json',
    success: function(data){
        callback(data)
    }

  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

3.Use promise

$(document).ready(function() {
  var response = ajaxcall().then(response=>{
     console.log(response)
  })

});
function ajaxcall(callback){
  return new Promise((resolve, reject) => {
   $.ajax({
          url: "https://jsonplaceholder.typicode.com/users/1",
          type: "GET",
          dataType: 'json',
          success: function(data){
              // success
              resolve(data)
          },
          error: function(e){
             reject(e)
          }

      });

  })
   

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

NOTE: In the above example, I modified your example query a bit to make it work in the snippet code.

So in your case you have to re-add your headers parameters

url: "url",
type: "POST",
data: form_data,
dataType: 'json',
contentType: false,
cache: false,
processData:false,
  • Related