Skip to content Skip to sidebar Skip to footer

How To Grab Return Value From An Ajax Call?

I wanted to grab the value on an ajax call using a function. but the value always return as undefined. return value is only 1 or 0. Here is my code: $(function(){ $('#add_produ

Solution 1:

It's asynchronous, so you have to wait for the ajax call to get the data back before you can alert it. You can do that easily by returning the ajax call and using done(), like so:

$(function() {
    $('#add_product').click(function() {
        var i   = $('#product_name').val(),
            par = 'product_name=' + i;

        check_product(par).done(function(value) {
            alert(value); //waits until ajax is completed
        });

        returnfalse;
    });
});

functioncheck_product(param) {
    return $.ajax({
        type : 'POST',
        data : param,
        url  : baseurl + 'cart/check_product_name/'
    });
}​

Solution 2:

Add this to ajax options:

dataType:"json",

and use

return Json(dataObject, JsonRequestBehavior.AllowGet);

in your action method.

Your

return result;

in the success handler of ajax is not a return for check_product. Pass another function (possibly anonymous) to check_product and call on ajax success.

Post a Comment for "How To Grab Return Value From An Ajax Call?"