Posted inJavaScript / jQuery

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.

I am Jaydeep Gondaliya , a software engineer, the founder and the person running Pakainfo. I'm a full-stack developer, entrepreneur and owner of Pakainfo.com. I live in India and I love to write tutorials and tips that can help to other artisan, a Passionate Blogger, who love to share the informative content on PHP, JavaScript, jQuery, Laravel, CodeIgniter, VueJS, AngularJS and Bootstrap from the early stage.

Leave a Reply

Your email address will not be published. Required fields are marked *

We accept paid guest Posting on our Site : Guest Post Chat with Us On Skype