Deviland
Deviland

Reputation: 3374

JQuery AJAX response undefined

I have a strange (probably not for some I would wager) problem, I have a JavaScript method to call all of my ajax calls, please see below.

function ajaxCall(url, params) {
if (params === null) {
    $.ajax({
        type: 'POST',
        url: url,
        contentType: 'application/json; charset=utf-8',
        dataType: 'json'
    }).success(function(response) {
        return response;
    }).error(function(response) {
        return response;
    });
} else {
    var data = JSON.stringify(params);
    $.ajax({
        type: 'POST',
        url: url,
        data: data,
        contentType: 'application/json; charset=utf-8',
        dataType: 'json'
    }).success(function(response) {
        return response;
    }).error(function(response) {
        return response;
    });
  }
}

when I call this method I get the appropriate response from the AJAX call and all looks rosy, until I return the response the call is returned undefined?

for completeness I will include my call code.

var call = ajaxCall(someUrl, someParams);

just to clarify and make sure my ramblings are understood call would be undefined in the above example?

Upvotes: 1

Views: 8187

Answers (2)

Avi Pinto
Avi Pinto

Reputation: 4336

you can't do that because the ajax call is async,
$.ajax returns a Deferred Object and you can work with it to get what you need read on it here

Upvotes: 1

Parv Sharma
Parv Sharma

Reputation: 12705

the ajax call is async by nature and dosent return anything. so when you do something like this

var call = ajaxCall(someUrl, someParams);

then a request is sent to the server and next lines begins to execute. without putting the value in the call variable;

also code like this

.success(function(response) {
        return response;

would do nothing as .success() takes a function or rather a callback to execute when the response is successfull so if u return something in this and put the async flag in the $.ajax() options to true. then also nothing/undefined will be returned.

Upvotes: 1

Related Questions