How to grab return value from an ajax call?
ajax, javascript, jquery
Solution
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
});
return false;
});
});
function check_product(param) {
return $.ajax({
type : 'POST',
data : param,
url : baseurl + 'cart/check_product_name/'
});
}
Problem
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_product').click(function(){ var i = $('#product_name').val(); param = 'product_name='+i; var value = check_product(param); alert(value); return false; }); }); function check_product(param){ $.ajax({ type : 'POST', data : param, url : baseurl+'cart/check_product_name/', success : function(result){ //alert(result); return result; } }); } ``` I am still working on getting this one work. I get the value now showing 1 or 0. What im trying to accomplish now is how I can it in the if statement. I wanted to have something like this. If val = 0 return true; else return false. Im not sure I'm in the right track of using the ajax function. But if there a better way you can show me I will appreciate it. ``` $(function(){ $('#add_product').click(function(){ var i = $('#product_name').val(); param = 'product_name='+i; check_product(param).done(function(value) { var val = value; //waits until ajax is completed }); if(val == 0){ return true; } else{ return false; } }); }); function check_product(param){ return $.ajax({ type : 'POST', data : param, url : baseurl+'cart/check_product_name/' }); } ```