122

I have a small problem with jQuery $.ajax() function.

I have a form where every click on the radio button or selection from the dropdown menu creates a session variable with the selected value.

Now - I have one of the dropdown menus which have 4 options - the first one (with label None) has a value="" other have their ids.

What I want to happen is to None option (with blank value) to remove the session and other to create one, but only if session with this specific select name doesn't already exist - as all other options have the same amount assigned to it - it's just indicating which one was selected.

I'm not sure if that makes sense - but have a look at the code - perhaps this will make it clearer:

$("#add_ons select").change(function() {
        // get current price of the addons
        var order_price_addon = $(".order_price_addon").text();
        // get price of the clicked radio button from the rel attribute
        var add = $(this).children('option').attr('label');
        var name = $(this).attr('name');
        var val = $(this).val();
        
        
        if(val == "") {
            var price = parseInt(order_price_addon) - parseInt(add);
            removeSession(name);
        } else {
            if(isSession(name) == 0) {
                var price = parseInt(order_price_addon) + parseInt(add);
            }   
            setSession(name, val);              
        }
        
        $(".order_price_addon").html(price);    
        setSession('order_price_addon', price);         
        updateTotal();
});

so - first of all when the #add_ons select menu triggers "change" we get some values from a few elements for calculations.

we get the label attribute of the option from our select which stores the value to be added to the total, name of the select to create session with this name and value to later check which one was selected.

now - we check whether the val == "" (which would indicate that None option has been selected) and we deduct the amount from the total as well as remove the session with the select's name.

After this is where the problem starts - else statement.

Else - we want to check whether the isSession() function with the name of our selector returns 0 or 1 - if it returns 0 then we add to the total the value stored in the label attribute, but if it returns 1 - that would suggest that session already exists - then we only change the value of this session by recreating it - but the amount isn't added to it.

Now isSession function looks like this:

function isSession(selector) {
    $.ajax({
        type: "POST",
        url: '/order.html',
        data: ({ issession : 1, selector: selector }),
        dataType: "html",
        success: function(data) {
            return data;
        },
        error: function() {
            alert('Error occured');
        }
    });
}

Now - the problem is - that I don't know whether using return will return the result from the function - as it doesn't seem to work - however, if I put the "data" in the success: section into the alert() - it does seem to return the right value.

Does anyone know how to return the value from the function and then compare it in the next statement?


Thanks guys - I've tried it in the following way:

function isSession(selector) {
    $.ajax({
        type: "POST",
        url: '/order.html',
        data: ({ issession : 1, selector: selector }),
        dataType: "html",
        success: function(data) {
            updateResult(data);
        },
        error: function() {
            alert('Error occured');
        }
    });
}

then the updateResult() function:

function updateResult(data) {
    result = data;
}

result - is the global variable - which I'm then trying to read:

$("#add_ons select").change(function() {
        // get current price of the addons
        var order_price_addon = $(".order_price_addon").text();
        // get price of the clicked radio button from the rel attribute
        var add = $(this).children('option').attr('label');
        var name = $(this).attr('name');
        var val = $(this).val();
        
        
        if(val == "") {
            var price = parseInt(order_price_addon) - parseInt(add);
            removeSession(name);
        } else {
            isSession(name);
            if(result == 0) {
                var price = parseInt(order_price_addon) + parseInt(add);
            }   
            setSession(name, val);              
        }
        
        $(".order_price_addon").html(price);    
        setSession('order_price_addon', price);         
        updateTotal();
    });

but for some reason - it doesn't work - any idea?

2

10 Answers 10

135

The trouble is that you can not return a value from an asynchronous call, like an AJAX request, and expect it to work.

The reason is that the code waiting for the response has already executed by the time the response is received.

The solution to this problem is to run the necessary code inside the success: callback. That way it is accessing the data only when it is available.

function isSession(selector) {
    $.ajax({
        type: "POST",
        url: '/order.html',
        data: ({ issession : 1, selector: selector }),
        dataType: "html",
        success: function(data) {
            // Run the code here that needs
            //    to access the data returned
            return data;
        },
        error: function() {
            alert('Error occured');
        }
    });
}

Another possibility (which is effectively the same thing) is to call a function inside your success: callback that passes the data when it is available.

function isSession(selector) {
    $.ajax({
        type: "POST",
        url: '/order.html',
        data: ({ issession : 1, selector: selector }),
        dataType: "html",
        success: function(data) {
                // Call this function on success
            someFunction( data );
            return data;
        },
        error: function() {
            alert('Error occured');
        }
    });
}

function someFunction( data ) {
    // Do something with your data
}
4
  • 15
    You CAN return a value from an AJAX request, but that's only if you make it non-asynchronous (set the option async: false). In some cases, having an asynchronous call is not requirement. More on jquery.ajax() doc api.jquery.com/jQuery.ajax , not that As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated;
    – Adriano
    Jul 12, 2013 at 9:05
  • 57
    "Non-asynchronous" can of course also be referred to as "synchronous" ;) Feb 3, 2014 at 17:43
  • in both methods you suggested; ie. run the function withing success, then you have to write multiple ajax for different scenarios. this won't help in creating a global ajax wrapper , engine.
    – wpcoder
    Nov 3, 2017 at 22:45
  • It seems, async: false is now deprecated and all of the processing needs to be done in the callback functions. Jun 30, 2020 at 18:27
41

There are many ways to get jQuery AJAX response. I am sharing with you two common approaches:

First:

use async=false and within function return ajax-object and later get response ajax-object.responseText

/**
 * jQuery ajax method with async = false, to return response
 * @param  {mix}  selector - your selector
 * @return {mix}           - your ajax response/error
 */
function isSession(selector) {
    return $.ajax({
        type: "POST",
        url: '/order.html',
        data: {
            issession: 1,
            selector: selector
        },
        dataType: "html",
        async: !1,
        error: function() {
            alert("Error occured")
        }
    });
}
// global param
var selector = !0;
// get return ajax object
var ajaxObj = isSession(selector);
// store ajax response in var
var ajaxResponse = ajaxObj.responseText;
// check ajax response
console.log(ajaxResponse);
// your ajax callback function for success
ajaxObj.success(function(response) {
    alert(response);
});

Second:

use $.extend method and make a new function like ajax

/**
 * xResponse function
 *
 * xResponse method is made to return jQuery ajax response
 * 
 * @param  {string} url   [your url or file]
 * @param  {object} your ajax param
 * @return {mix}       [ajax response]
 */
$.extend({
    xResponse: function(url, data) {
        // local var
        var theResponse = null;
        // jQuery ajax
        $.ajax({
            url: url,
            type: 'POST',
            data: data,
            dataType: "html",
            async: false,
            success: function(respText) {
                theResponse = respText;
            }
        });
        // Return the response text
        return theResponse;
    }
});

// set ajax response in var
var xData = $.xResponse('temp.html', {issession: 1,selector: true});

// see response in console
console.log(xData);

you can make it as large as you want...

4
  • Nice idea but ajaxObj['responseText'] doesn't exist when you're defining var ajaxResponse
    – mu3
    Aug 20, 2014 at 1:27
  • Perfect!! your first solution saved me May 5, 2015 at 11:02
  • second method is 100% A OK! ;) Feb 24, 2016 at 14:27
  • 7
    As of jQuery 1.8, the use of async: false is deprecated!
    – gatteo
    Feb 25, 2017 at 14:14
19

Although all the approaches regarding the use of async: false are not good because of its deprecation and stuck the page untill the request comes back. Thus here are 2 ways to do it:

1st: Return whole ajax response in a function and then make use of done function to capture the response when the request is completed.(RECOMMENDED, THE BEST WAY)

function getAjax(url, data){
    return $.ajax({
        type: 'POST',
        url : url,              
        data: data,
        dataType: 'JSON',
        //async: true,  //NOT NEEDED
        success: function(response) {
            //Data = response;
        }
    });
 }

CALL THE ABOVE LIKE SO:

getAjax(youUrl, yourData).done(function(response){
    console.log(response);
});

FOR MULTIPLE AJAX CALLS MAKE USE OF $.when :

$.when( getAjax(youUrl, yourData), getAjax2(yourUrl2, yourData2) ).done(function(response){
    console.log(response);
});

2nd: Store the response in a cookie and then outside of the ajax call get that cookie value.(NOT RECOMMENDED)

        $.ajax({
            type: 'POST',
            url : url,              
            data: data,
            //async: false,    // No need to use this
            success: function(response) {
                Cookies.set(name, response);
            }
        });

        // Outside of the ajax call
        var response = Cookies.get(name);

NOTE: In the exmple above jquery cookies library is used.It is quite lightweight and works as snappy. Here is the link https://github.com/js-cookie/js-cookie

2
  • The first method is outputting my whole PHP code instead of the echo output. Jul 22, 2021 at 12:27
  • @AldrinSaurovSarker Make sure your datatype is correct and your server is accepting it.
    – MR_AMDEV
    Oct 27, 2023 at 15:21
16

I saw the answers here and although helpful, they weren't exactly what I wanted since I had to alter a lot of my code.

What worked out for me, was doing something like this:

function isSession(selector) {
    //line added for the var that will have the result
    var result = false;
    $.ajax({
        type: "POST",
        url: '/order.html',
        data: ({ issession : 1, selector: selector }),
        dataType: "html",
        //line added to get ajax response in sync
        async: false,
        success: function(data) {
            //line added to save ajax response in var result
            result = data;
        },
        error: function() {
            alert('Error occured');
        }
    });
    //line added to return ajax response
    return result;
}

Hope helps someone

anakin

2
  • 6
    You actually just turn off async Apr 6, 2016 at 0:32
  • async: false is very helpful. Nov 1, 2022 at 8:51
8

With Help from here

function get_result(some_value) {
   var ret_val = {};
   $.ajax({
       url: '/some/url/to/fetch/from',
       type: 'GET',
       data: {'some_key': some_value},
       async: false,
       dataType: 'json'
   }).done(function (response) {
       ret_val = response;
   }).fail(function (jqXHR, textStatus, errorThrown) {
           ret_val = null;
       });
   return ret_val;
}

Hope this helps someone somewhere a bit.

1
  • 1
    The use of async: false, is prehistoric and is deprecated since jQuery v1.8, It will probably help no one
    – Alon Eitan
    Jul 11, 2019 at 13:03
8

EDIT: This is quite old, and ugly, don't do this. You should use callbacks: https://stackoverflow.com/a/5316755/591257

EDIT 2: See the fetch API

Had same problem, solved it this way, using a global var. Not sure if it's the best but surely works. On error you get an empty string (myVar = ''), so you can handle that as needed.

var myVar = '';
function isSession(selector) {
  $.ajax({
    'type': 'POST',
    'url': '/order.html',
    'data': {
      'issession': 1,
      'selector': selector
    },
    'dataType': 'html',
    'success': function(data) {
      myVar = data;
    },
    'error': function() {
      alert('Error occured');
    }
  });
  return myVar;
}
3
  • 9
    you also need to add async: false here, because in asynchronous-mode it's not guaranteed that data is saved into myVar before myVar is returned.
    – low_rents
    Jul 3, 2014 at 9:22
  • @low_rents, thanks for this comment. I had a problem returning a value from an ajax call and this was the first thread I found (after many) that mentioned async: false. Worked perfectly for me.
    – John Cowan
    Dec 6, 2021 at 20:33
  • Absolutely @low_rents but please don't realy on this answer, things have moved a lot since.
    – aesede
    Dec 7, 2021 at 18:54
3

Add async: false to your attributes list. This forces the javascript thread to wait until the return value is retrieved before moving on. Obviously, you wouldn't want to do this in every circumstance, but if a value is needed before proceeding, this will do it.

14
  • 4
    You should never ever set async: false. This blocks everyhing on the page for the duration of the retrieval. You know what the A in AJAX stands for: Asynchronous. The proper answer would be that OP needs to use the success() callback properly.
    – nietonfir
    Nov 1, 2013 at 20:49
  • 2
    I acknowledged the fact that everything has to wait. Under certain circumstances, the calling function may need a returned value, such as adding a new record and needing a record id returned. Once you know the rules, you know when they can be broken. Never say never. Here's someone else who concurs. (stackoverflow.com/questions/3880361/…)
    – Hoodlum
    Dec 20, 2013 at 19:05
  • 1
    @CharlesWood Solely for those who can't grasp the async nature of ajax.
    – nietonfir
    Feb 4, 2014 at 9:04
  • 1
    @nietonfir : if you should never ever use async: false why would have jQuery implemented this option? if i don't load big amounts of data to the page and just handle an user event, it's ok that it blocks everything else in the short amount of time for that particular user. nothing wrong and nothing bad about it. (if used correctly it won't block anything because in that particular time no other actions for that particular user will occur)
    – low_rents
    Jul 3, 2014 at 9:14
  • 1
    @northkildonan No, it's not okay. A sync AJAX request is bad. It blocks the complete javascript thread with something that you can't control. You don't have control over the amount of time it may take to process the request: the connection might be unreliable, the server might take longer than expected, etc. The only reason it is in jQuery is that you might need to save data on page unload (the only place it doesn't really matter if it takes longer, as the user already expressed his desire to leave the page). Just look at the jQuery unit tests…
    – nietonfir
    Jul 3, 2014 at 12:34
2
// Common ajax caller
function AjaxCall(url,successfunction){
  var targetUrl=url;
  $.ajax({
    'url': targetUrl,
    'type': 'GET',
    'dataType': 'json',
    'success': successfunction,
    'error': function() {
      alert("error");
    }
  });
}

// Calling Ajax
$(document).ready(function() {
  AjaxCall("productData.txt",ajaxSuccessFunction);
});

// Function details of success function
function ajaxSuccessFunction(d){
  alert(d.Pioneer.Product[0].category);
}

it may help, create a common ajax call function and attach a function which invoke when success the ajax call, see the example

-1

Hi try async:false in your ajax call..

0
-1
function get_rows(param) {
   var rows = '';
   $.ajax({
       url: 'https://www.exmple.com/test.php',
       type: 'POST',
       data: {'key': value},
       async: false,
       dataType: 'html'
   }).done(function (data) {
       rows = data;
   }).fail(function (jqXHR, textStatus, errorThrown) {
       rows = '';
   });
   return rows;
}

I recommend use async: false. It is very very helpful.

Not the answer you're looking for? Browse other questions tagged or ask your own question.