Kalaivani
Kalaivani

Reputation: 485

How to return Jquery ajax call value?

How to return value in function which calls jquery ajax. I approached following method and I dont know whether it is correct or not

function a(){
var a=ajaxFunction();
}

$.ajax({
    url: "Handler.ashx",
    cache: false,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        _testId = data.Id;
    }

return _testId

});

but in var a, value is undefined. The value of _testId is not returned by using above method. If it is wrong please tell me the right approach.

Upvotes: 0

Views: 355

Answers (3)

Alfonso
Alfonso

Reputation: 326

I'd probably do this:

var _testID = false;

function a(){
    ajaxFunction();
    if(_testID)
    {
        //Do what you need here
    }
}

$.ajax({
    url: "Handler.ashx",
    cache: false,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        _testId = data.Id;
    }
});

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

Because the AJAX call is run asynchronously the return statement will be hit before the call has completed, therefore the value being returned is always undefined.

You need to change your logic to deal with the result of the AJAX call within the success handler ONLY:

$.ajax({
    url: "Handler.ashx",
    cache: false,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        _testId = data.Id;

        // do whatever you need with _testId in here.
        // You can pass it to another function if you require to modularise your logic, eg.
        processResult(data)
    }
});

function processResult(json) {
    // do stuff with your json here
}

Upvotes: 0

Mathias Bynens
Mathias Bynens

Reputation: 149544

You’ll need to use a callback function, as the A in “Ajax” stands for “asynchronous”.

$.ajax({
    'url': 'Handler.ashx',
    'cache': false,
    'contentType': 'application/json; charset=utf-8',
    'dataType': 'json',
    'success': callback
);

function callback(data) {
  var testID = data.id;
  console.log(testID);
}

You could use an anonymous function to inline it as well:

$.ajax({
    'url': 'Handler.ashx',
    'cache': false,
    'contentType': 'application/json; charset=utf-8',
    'dataType': 'json',
    'success': function(data) {
      var testID = data.id;
      console.log(testID);  
    }
);

All the code that depends on the Ajax results should be handled in the callback.

Upvotes: 1

Related Questions