0

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.

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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
}

Comments

0

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;
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.