For my Phonegap/Cordova project I'm trying to handle all ajax calls with the following functions:
function requestData(action, id ) {
var data = {
user_id: localStorage.getItem('user_id')
};
if( action == 'feed_load_feedings' || action == 'feed_add_load_menu_weight' || action == 'feed_add_load_menu_supps' ) {
data.id = id;
}
$.ajax({
type: 'post',
url: 'http://_______.com/file.php?'+action,
async: false,
crossDomain: true,
data: data,
beforeSend: showLoader,
error: handleError,
success: handleSuccess
});
}
function showLoader() {
console.log('showLoader fired')
$('body').prepend('<p id="loading">De gegevens worden geladen...</p>');
}
function handleError(data) {
console.log('handleError fired')
$('#loading').remove();
$('body').prepend('<p id="error">Fout tijdens het laden van de gegevens...</p>');
return false;
}
function handleSuccess(data) {
console.log('handleSuccess fired')
$('#loading').remove();
if( typeof data !== 'object' ) {
$('body').prepend('<p id="error">Fout in gegevens object...</p>');
return false;
}
else if(data.length == 0 ) {
return 0;
}
else {
return data;
}
}
This handles the request, but also the error handling.
If everything is alright, it should return the data. However using this:
$(function() {
var herd = requestData('herd_load_herds');
console.log(herd):
});
Gives this in the console:
showLoader fired
POST http://_______.com/file.php?feed_load_feedings
handleSuccess fired
undefined
In the POST request I can see that the data is called and okay. However it isn't put into the variable. I thought that adding async: false
to my ajax call would prevent that. What am I overseeing?