0

I realize this is asked a lot and usually the answer is that AJAX is asynchronous and this is why it's returning undefined, but even though I set my async to false here, it's still returning undefined when the function is called. res is always undefined

function sendRequest(link, type, query) {
    $(document).ready(function(){
        $.ajax({
            'url' : link,
            'type' : type,
            'data' : query,
            'async' : false,
            'dataType': "json",
            'headers': {
                'Cache-Control':'max-age=0',
                'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
                'Content-Type':'application/x-www-form-urlencoded',
                'Accept-Language':'en-US,en;q=0.8,ar;q=0.6',
            }, 
            'success': function(data) {
                var res = data;
            }
        });
    });
    return res;
} 

Also I am sure that the request is being sent correctly and that the response is received correctly as well

Ali
  • 3,479
  • 4
  • 16
  • 31
  • 2
    1) Don't use `async: false`. Bad. 2) The `var` scopes the variable to the callback function so it isn't accessible outside that function. – Jason P May 28 '14 at 19:25
  • In "var res" var define the scope, res doesn´t exist out from function called from success – Samuel May 28 '14 at 19:27

5 Answers5

2

You'll have to declare and assign res separately.

var res;

$.ajax({
    // ...
    'success': function (data) {
        res = data;
    }
});

return res;

Currently, res is being declared as a local variable solely inside the success callback. So, it won't be accessible to the rest of sendRequest().


Though, you should try to avoid using async: false with Ajax.

You can instead return the Deferred jqXHR provided by $.ajax(), allowing the calling function to add its own handler.

function sendRequest(link, type, query) {
    return $.ajax({
        // ...
    });
}

sendRequest(...).done(function (data) {
    // ...
});

More details and options are described in "How to return the response from an AJAX call?"

Community
  • 1
  • 1
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
  • Even after fixing the scope, it's still returning undefined. – Ali May 28 '14 at 19:32
  • @Ali With the snippet I suggested, `res` will only be assigned on `success`. Is the request `error`ing instead? – Jonathan Lonowski May 28 '14 at 19:34
  • No. It's running perfectly. It's receiving the response too. I check that using an HTTP Request monitor – Ali May 28 '14 at 19:35
  • @Ali The request can still `error` when jQuery attempts to parse the response, despite a `200` status. Is the response, in its entirety, a single, [valid](http://jsonlint.com/) JSON value? – Jonathan Lonowski May 28 '14 at 19:37
2

I think a better approach would be to have your sendRequest function return a jQuery Promise Object. As an example

function sendRequest(link, type, query) {
  return $.ajax({
        'url' : link,
        'type' : type,
        'data' : query,
        'dataType': "json",
        'headers': {
            'Cache-Control':'max-age=0',
            'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Content-Type':'application/x-www-form-urlencoded',
            'Accept-Language':'en-US,en;q=0.8,ar;q=0.6',
        }
    });
}

To use

sendRequest('/someurl', 'GET', {}).done(function(data) {
  // do whatever you need with data here
});
Bart Jedrocha
  • 11,450
  • 5
  • 43
  • 53
0

Firstly res should be outside ajax scope, and Secondly function will return before ajax call completes thats the reason its undefined:

 $(document).ready(function(){
        $.ajax({
            'url' : link,
            'type' : type,
            'data' : query,
            'async' : false,
            'dataType': "json",
            'headers': {
                'Cache-Control':'max-age=0',
                'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
                'Content-Type':'application/x-www-form-urlencoded',
                'Accept-Language':'en-US,en;q=0.8,ar;q=0.6',
            }, 
            'success': function(data) {
                MyFunction(data);
            }
        });


function MyFunction(data)
{

// do with ajax resonse what is needed
}
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
0

It's a scope problem. You need to declare var res; in a scope that's accessible to the return, and just update that object inside of the AJAX.

function sendRequest(link, type, query) {
    var res;
    $(document).ready(function(){
        $.ajax({
            //...
            'success': function(data) {
                res = data;
            }
        });
    });
    return res;
} 
mmm
  • 2,272
  • 3
  • 25
  • 41
0

AJAX is async (at least it should be, I would refrain from using async set to false), so the result will be undefined. Use a callback:

function sendRequest(link, type, query, callback) {
    $.ajax({
       ..
       ..
       'success': function(data) {
            callback(data);
        }
    });
}

sendRequest(link, type, query, function(data) {
    console.log(data); //YOUR DATA
});
tymeJV
  • 103,943
  • 14
  • 161
  • 157