how to return value from ajax success function in javascript?

Today, We want to share with you how to return value from ajax success function in javascript.In this post we will show you jquery ajax success: function return data, hear for how to get value from ajax response in javascript we will give you demo and example for implement.In this post, we will learn about return value from javascript ajax call with an example.

how to return value from ajax success: function in jquery?

jquery Code

function follow() {
    getProducts(function(d) {
        //processing the data
        console.log(d);
    });
}

function getProducts(callback) {
    var data;
    $.ajax({
        url: 'url',
        data: 'all product data to send',
        success: function (resp) {
            data = resp;
            callback(data);
        },
        error: function () {}
    }); // ajax asynchronus request 
    //the following line wouldn't work, since the function returns immediately
    //return data; // return data from the ajax request
}

Example 2:

function getDataFromTheServer(url) { 
  var defer = $.Deferred(); 
 
  $.ajax({ 
    url: 'http://www.your-http-url.com', 
    dataType: 'json', 
    success: function(response) { 
      defer.resolve(response) 
    }, 
    error: function(req, status, err) { 
      defer.reject(err); 
    } 
  }); 
 
  return defer.promise(); 
} 
 
getDataFromTheServer() 
.then(function(response) { 
  var productDataObject = JSON.parse(response); 
 
  return productDataObject.prop1; 
}) 
.fail(function(err) { 
  console.log(err); 
}) 
getDataFromTheServer() 
.then(function(response) { 
  var productDataObject = response.text; 
 
  return productDataObject.prop1; 
}) 
.then(function(prop1) { 
  var uppercase prop1.toLowerCase(); 
 
  return uppercase; 
}) 
.then(function(uppercase) { 
  // etc 
}) 
.fail(function(err) { 
  console.log(err) 
}); 

I hope you get an idea about how to get return value from ajax call.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Comment