Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery - return value using ajax result on success

Tags:

jquery

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?

like image 784
user398341 Avatar asked Jul 21 '10 18:07

user398341


People also ask

How do I return data after ajax call success?

You can store your promise, you can pass it around, you can use it as an argument in function calls and you can return it from functions, but when you finally want to use your data that is returned by the AJAX call, you have to do it like this: promise. success(function (data) { alert(data); });

How check ajax request is successful jQuery?

$. ajax({ url: "page. php", data: stuff, success: function(response){ console. log("success"); } });

How can a function return a value in ajax?

ajax({ async: true, contentType: 'application/json; charset=utf-8', type: "POST", dataType: 'json', data: JSON. stringify(arrays), url: "MyHandler. ashx", success: function (result) { b = true; }, error: function () { alert('Error occurred'); } });


2 Answers

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 } 
like image 121
user113716 Avatar answered Oct 03 '22 11:10

user113716


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...

like image 23
Nono Avatar answered Oct 03 '22 13:10

Nono