JavaScript Undefined with jQuery deferred

13,259

Solution 1

You don't need to use jQuery.Deferred() here, $.ajax handles this for you. You just need to return $.ajax({}). Also, since AJAX is asynchronous, your issueData = data; won't do anything useful.

You need to use callbacks to get the returned data.

You can do this:

function getIssues() {
    return $.ajax({
        url: 'http://localhost:49650/Issues.svc/GetIssues',
        type: 'GET',
        dataType: 'json',
        error: function () {
            alert('Call not resolved')
        }
    }); 
}

getIssues().done(function(data){
    // use the returned JSON here
});

Or, you can use the success function:

function getIssues() {
    return $.ajax({
        url: 'http://localhost:49650/Issues.svc/GetIssues',
        type: 'GET',
        dataType: 'json',
        success: function(data){
            // use the returned JSON here
        },
        error: function () {
            alert('Call not resolved')
        }
    }); 
}

getIssues();

Solution 2

A $.resolve() statement is missing and you have two 'return' statement, the second 'return' is never reached.

A solution is this:

 function getIssues(issueData) {
   var deferred = jQuery.Deferred();
   $.ajax({
    url: 'http://localhost:49650/Issues.svc/GetIssues',
    type: 'GET',
    dataType: 'json',
    success: function(data) {
        var receivedData = data;
        ....    
        deferred.resolve();
    },
    error: function () {
        alert('Call not resolved')
    }
   });
   return deferred.promise();    
 }
Share:
13,259
Alexander
Author by

Alexander

Building this and that here and there.

Updated on June 14, 2022

Comments

  • Alexander
    Alexander almost 2 years

    I am trying to write an AJAX request using the jQuery .Deferred/.promise. The function gets hit when the page loads and then nothing happens and I can't access my issueData variable. When I run the function it is undefined, but my AJAX call return JSON objects. I'm trying to figure out if the issue is in how I setup the issueData .deferred() and .promise()

    function getIssues(issueData) {
        var issueData = new jQuery.Deferred();
        return $.ajax({
            url: 'http://localhost:49650/Issues.svc/GetIssues',
            type: 'GET',
            dataType: 'json',
            success: function(data) {
                issueData = data;
            },
            error: function () {
                alert('Call not resolved')
            }
        });
        return issueData.promise();    
    }
    
  • Kevin B
    Kevin B almost 11 years
    The resolve doesn't really do anything since he doesn't return issueData from getIssues.