Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Return value undefined

Tags:

jquery

FIXED! THANKS! See "Corrected Code" below.

The goal is to get data back from the dialog box. I have seen lots of articles, but could not get any of them to work, so I decided to use a web service to pass the data back and forth between the dialog box and the underlying page.

All of the code is in place except the code that reads values coming back from the web service. I can see in the debugger that the data is being passed back, but when I return to the caller, the returned data is undefined.

jQuery function getLocal calls AJAX, gets good data back, but when it returns to the function that calls it (verbListShow), the returned value is "undefined".

This is all happening in an ASP.NET page that is written largely in jQuery, and opens a jQuery dialog box.

function getLocal(name) {
    $.ajax({
        type: "POST",
        async: false,
        url: "WebServices/FLSAService.asmx/GetLocalVariable",
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({ name: name }),
        success: function (data) {
            var rtn = data.d;
            return rtn;
        }
    });
}

The above code works, but when called, rtn is undefined. Here is the caller:

function verbListShow(dutyNumber) {

    $('#dlgDutyList').dialog({
        modal: true,
        show: "slide",
        width: 250,
        height: 250,
        open: function (event, ui) {
            setLocal("DUTYNUMBER", dutyNumber);
        },
        buttons: {
            "Select": function () {
                var id = getLocal("VERBID"); // <*** Returns undefined
                var verb = getLocal("VERB"); // <*** Returns undefined
                $.ajax({
                    type: "POST",
                    async: false,
                    url: "WebServices/FLSAService.asmx/SetDuty",
                    dataType: 'json',
                    contentType: 'application/json; charset=utf-8',
                    data: JSON.stringify({ dutyNum: dutyNumber, id: id, verb: verb }),
                    success: function (data) {
                        data = $.parseJSON(data.d);
                        if (data.ErrorFound) {
                            showMessage(data.ErrorMessage, 2, true);
                        }
                        else {
                            log('Set Duty: ' + data.StringReturn + ' (' + data.intReturn + ')');
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert("updateDuty: "
                            + XMLHttpRequest.responseText);
                    }
                });

                $(this).dialog("close");
            },
            Cancel: function () {
                $(this).dialog("close");
            }
        }

    });
    $('#dlgDutyList').dialog('open');

FIXED CODE:

function getLocal(name) {
var rtn = "";
    $.ajax({
        type: "POST",
        async: false,
        url: "WebServices/FLSAService.asmx/GetLocalVariable",
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({ name: name }),
        success: function (data) {
            rtn = data.d;
        }
    });
return rtn;
}
like image 869
Bob Jones Avatar asked Dec 12 '12 20:12

Bob Jones


People also ask

Why I get undefined in jQuery?

Common causes of 'jQuery is undefined'Incorrect load order of JavaScript assets. jQuery source can't be loaded/found. Conflicting plugins/libraries/code. Framework implementation issues.

Why AJAX return undefined?

ajax() is asynchronous, so immediately after executing the statement, the outer function returns, so there is no return value of the outer function, that's why you're getting undefined .


2 Answers

It defeats the purpose of AJAX to use it synchronously (AJAX stands for Asynchronous Javascript And Xml).

Now you cannot return a value from the success method, but you can store it in a variable and then return that

function getLocal(name) {
    var returnValue;
    $.ajax({
        type: "POST",
        async: false,
        url: "WebServices/FLSAService.asmx/GetLocalVariable",
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({ name: name }),
        success: function (data) {
            returnValue = data.d;
        }
    });
    return returnValue;
}

But the proper way would be to use a deferred object

function getLocal(name, resultset) {
    return $.ajax({
        type: "POST",
        url: "WebServices/FLSAService.asmx/GetLocalVariable",
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({ name: name }),
        success: function (data) {
            resultset[name] = data.d;
        }
    });
}

and call it

"Select": function() {
    var results = {};
    var self = this;
    $.when(getLocal("VERBID", results), getLocal("VERB", results)).then(function(){
        $.ajax({
            type: "POST",
            url: "WebServices/FLSAService.asmx/SetDuty",
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify({
                dutyNum: dutyNumber,
                id: results.VERBID,
                verb: results.VERB
            }),
            success: function(data) {
                data = $.parseJSON(data.d);
                if (data.ErrorFound) {
                    showMessage(data.ErrorMessage, 2, true);
                }
                else {
                    log('Set Duty: ' + data.StringReturn + ' (' + data.intReturn + ')');
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert("updateDuty: " + XMLHttpRequest.responseText);
            }
        });
    }).always(function(){
        $(self).dialog("close");
    });
}
like image 149
Gabriele Petrioli Avatar answered Oct 20 '22 00:10

Gabriele Petrioli


Everything is because $.ajax function don't return any value because of it's asynchronous behaviour, my advice is to make second parameter for getLocal method called "callback".

Proper way is to do it like so:

function getLocal(name, callback) {
    $.ajax({
        type: "POST",
        async: false,
        url: "WebServices/FLSAService.asmx/GetLocalVariable",
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({ name: name }),
        success: function (data) {
            var rtn = data.d;
            callback(rtn);
        }
    });
}

Then, your main code have to look like that (asynchronous code):

//some code here
buttons: {
            "Select": function () {
                getLocal("VERBID", function(id) {
                     getLocal("VERB", function(verb) { 
                        $.ajax({
                           type: "POST",
                           async: false,
                           url: "WebServices/FLSAService.asmx/SetDuty",
                           dataType: 'json',
                        //some code here
                     });
                });
//some code here

To improve this code, to make two asynchronous calls at once, you can use jQuery Deferred object, and run .resolve(data) on it just after all ajax calls obtained proper response.

like image 5
Wojciech Dłubacz Avatar answered Oct 20 '22 01:10

Wojciech Dłubacz