I'm working on a project that uses widespread AJAX calls. I'm stuck in one particular AJAX call where I need to assign the returned data to a variable. My code is below:
//ajax function function ajaxCall(url, type, data, dataType, callback) { var type = typeof type !== 'undefined' ? type : "post"; var dataType = typeof dataType !== 'undefined' ? dataType : "json"; $.ajax({url: url, data: "data=" + data, type: type, dataType: dataType, success: function(d){ if(type === "post") { if(d.hasOwnProperty('success') === false) { callback(false, d); //passes error message } else { callback(d.success === "1", ""); //data was successfully posted } } else { callback(true, d); //pass any returned data from HTTP GET } } }); } //function that gets data via ajax function getData(cat_id) { var d = new Object(); ajaxCall('http://localhost/fetch', 'get', cat_id, 'json', function(success, data){ if(success) { d = data; console.log(d); //prints returned JSON object correctly in console } }); return d; //<=== culprit? } var data = getData(19); console.log(data[1].cat_name); //prints Uncaught TypeError: Cannot read property '1' of undefined in Chrome console //in Firebug, it prints 'undefined'
I think this has to do with the fact that the ajaxCall() returns the variable "d" before the async call finishes. How can I make the function return only after the variable "d" has been assigned the returned data?
I tried:
function getData(cat_id) { var d = null; ajaxCall('http://localhost/fetch', 'get', cat_id, 'json', function(success, data){ if(success) { d = data; console.log(d); //prints returned JSON object correctly in console } }); while(d === null) { if(d !== null) { return d; } } }
but this loop keeps running forever and the page does not even load. Any help would be greatly appreciated.