rexhin rexhin - 5 months ago 5
JSON Question

Two callback functions are being executed in custom AJAX function

I have created a custom

GET
and
POST
function in javascript to handle my AJAX requests. When I try to make a call,
fail
callback is executed first and then the
done
callback. The response from AJAX is a valid JSON string and I do not understand why this is happening. Only
done
callback must be executed if the response is valid JSON.

get('ajax/autocomplete.php', {q: q}, function(data) {
//done, executed second
}, aww());//Error, executed first

function get() {
var data,
done,
fail,
done_index = null,
str = '',
ajax = new XMLHttpRequest(),
url = arguments[0];

for(var i=0; i<arguments.length; i++) {
if(typeof arguments[i] == 'object') {
data = arguments[i];

for(var key in data) {
if(str != "") str += "&";

str += key + "=" + encodeURIComponent(data[key]);
}

if(str != '') url += '?';
} else if(typeof arguments[i] == 'function') {
if(!done_index) {
done = arguments[i];
done_index = i;
}

if(i != done_index) {
fail = arguments[i];
}
}
}

ajax.onreadystatechange = function() {
console.log(ajax.readyState, ajax.status);

if(ajax.readyState === XMLHttpRequest.DONE && ajax.status === 200) {
var response = ajax.responseText;//treat empty response as valid JSON
if(response.length == 0) response = '""';

try {
var json = JSON.parse(response);
return (done) ? done(json) : false;
} catch(e) {
console.log(e);
return (fail) ? fail() : false;
}
}
};

ajax.open('get', url + str);
ajax.send();
}

Answer

You're calling the aww() function in the argument list to get(), because you have parentheses after it. You should just pass a reference to the function. It should be:

get('ajax/autocomplete.php', {q: q}, function(data) {
}, aww);
Comments