GreyRoofPigeon
GreyRoofPigeon

Reputation: 18123

jQuery ajax call to variable

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?

Upvotes: 2

Views: 86

Answers (2)

Vicky Gonsalves
Vicky Gonsalves

Reputation: 11717

The reason behind returning undefined is pretty obvious since requestData function doesn't return anything which means it indirectly returns undefined

The flow of the ajax is asynchronous, so returning anything in the function requestData won't work. You need to pass callback function in function calling and execute it in the success/ error handlers.

$(function() {
    requestData('herd_load_herds', 'someid', function(err, data){
      if(err){
        console.log("error");
        console.log(err);
      }else{
        console.log("success");
        console.log(data):
      }
    });    
});

in AJAX:

function requestData(action, id, callback) {
    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: function(error){
              handleError(error, callback);
            },
            success: function(data){
              handleSuccess(data, callback);
            }
        });
}

In handler:

function handleSuccess(data, next) {
    console.log('handleSuccess fired')
    $('#loading').remove();
    if( typeof data !== 'object' ) {
        $('body').prepend('<p id="error">Fout in gegevens object...</p>');
        next(undefined, false);
    }else{       
      next(undefined, data);
    }
}

function handleError(err, next) {
    console.log('handleError fired')
    $('#loading').remove();
    $('body').prepend('<p id="error">Fout tijdens het laden van de gegevens...</p>');
    next(err);
}

Upvotes: 3

Matthew Herbst
Matthew Herbst

Reputation: 32003

Your code is working perfectly fine. JavaScript functions without a return value return undefined by default. Your function requestData has no return <someValue> statement and so returns the default undefined.

If you want to save the data, you need to save it in the success callback.

My advise is to not try and hack around with async: false. Just do everything async and respond to callbacks appropriately.

Upvotes: 1

Related Questions