1

I have used the below code to get a value, but it is not working. The post method returns the correct value, but I want to assign the value to a variable, but it is not working. How can I fix?

$(document).ready(function () {
    var sessionID = GetSessionIDFromDB();
    alert(sessionID);
});

function GetSessionIDFromDB() {

    $.ajax({
        type: "POST",
        url: myurl + "GetSessionID",
        data: '{}',
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            var returnValue = $.parseJSON(data.d);
            return returnValue;
        }
    });
}

The returnValue in GetSessionIDFromDB is what I expect, but when assigned to a variable, it is null.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user3166407
  • 65
  • 2
  • 9
  • The `return returnValue` statement is in your `success` callback function and that is executing after the HTTP post has completed successfully. Please read [this](http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/) and also read on how JavaScript callbacks work in general – Hari Pachuveetil Aug 22 '14 at 16:20

2 Answers2

0

Unless you specifically returned a JSON string in data.d, data.d might already be a JavaScript object, in which case you can just use:

var returnValue = data.d;
return returnValue;

Or simply:

return data.d;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Stryner
  • 7,288
  • 3
  • 18
  • 18
  • That does not answer the question why the assigned variable (`sessionID`) has a null value. – Hari Pachuveetil Aug 22 '14 at 16:25
  • Sorry, I should have been clearer. In some earlier versions of JQuery, the [$.parseJSON](http://api.jquery.com/jquery.parsejson/) implementation returns null if you pass it an object ([see fiddle](http://jsfiddle.net/1y8nbbk5/)) – Stryner Aug 22 '14 at 16:33
  • 1
    Oh, I see my mistake now. Yes I'm wrong. Sorry. – Stryner Aug 22 '14 at 16:34
0

The reason your alert is failing is because your GetSessionIDFromDB function does not return any value. It only calls the jQuery.ajax and registers the anonymous function that includes the return returnValue statement as a callback.

As I mentioned on the comment to your question, please read more on the concepts of JavaScript callbacks - this is a good article that I could quickly google.

To make your code work, try this:

$(document).ready(function () {
  GetSessionIDFromDB();
});

function GetSessionIDFromDB() {

    $.ajax({
        type: "POST",
        url: myurl + "GetSessionID",
        data: '{}',
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            var returnValue = $.parseJSON(data.d);
            var sessionID = returnValue;
            alert(sessionID);
        }
    });
} 
Hari Pachuveetil
  • 10,294
  • 3
  • 45
  • 68