2

this may sound very easy to few of you, but i am not able to figure out why I am not able to get the return value, even after chceking many posts :(

function getMessageCount() {
                    var count;
                    $.ajax({
                        type: "POST",
                        url: "http://localhost:43390" + "/services/DiscussionWidgetService.asmx/GetMessageCount",
                        dataType: "json",
                        contentType: "application/json; charset=utf-8",
                        success: function (data) {                            
                            count = data.d;
                        } //success
                    });
                    return count;
                }

Now if I call var count = getMessageCount(); it gives me undefinted :( while inside the method count is coming correct, i.e. service is working fine.

5 Answers5

4

I agree with the first line by ahren that 'That's because the $.ajax() call is asynchronous.'

you could try adding a setting - async:false which is true by default. This makes the call synchronous.

you can edit your code as :

function getMessageCount() {
                var count;
                $.ajax({
                    type: "POST",
                    url: "http://localhost:43390" + "/services/DiscussionWidgetService.asmx/GetMessageCount",
                    dataType: "json",
                    async:false,
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {                            
                        count = data.d;
                    } //success
                });
                return count;
            }
shashidhar
  • 41
  • 1
  • Worked perfectly for me :) – Sali Hoo May 20 '14 at 22:03
  • This is highly NOT recommended though as the user experience is horrible. Assume a connection is lost or dropped the ui thread is locked indefinitely. Never use async false for these sorts of things. – JonH Aug 21 '15 at 23:59
3

That's because the $.ajax() call is asynchronous.

If you edit your code to something like:

function getMessageCount(callback) {
    var count;
    $.ajax({
       type: "POST",
       url: "http://localhost:43390" + "/services/DiscussionWidgetService.asmx/GetMessageCount",
       dataType: "json",
       contentType: "application/json; charset=utf-8",
       success: function (data) {                            
         count = data.d;

         if(typeof callback === "function") callback(count);
      } //success
   });
}

Then when you call it:

getMessageCount(function(count){
  console.log(count);
});
ahren
  • 16,803
  • 5
  • 50
  • 70
  • still getting undefined :( var noOfMessages; getMessageCount(function (count) { noOfMessages = count; }); –  Nov 18 '13 at 12:03
  • 1
    When are you checking `noOfMessages` ? You should be checking within that callback. – ahren Nov 18 '13 at 12:04
  • Please help community moderation by closing obvious duplicates like this question instead of answering them. – John Dvorak Nov 18 '13 at 12:06
  • Can't I do like this? var noOfMessages = getMessageCount(function (count) { return count; }); –  Nov 18 '13 at 12:15
  • Jan : It could be a duplicate for u, but I couldnt figure out how to solve it, so posted. –  Nov 18 '13 at 12:15
  • 1
    @user2614405 - nope. The anonymous function within `getMessageCount(...)` won't return to where you think it will return. You'll need to place the rest of your code within the callback. – ahren Nov 18 '13 at 12:15
  • Then, If I need to save it into another variable, there isnt any option? I need to pass this as a parameter for the option of a jquery Widget. –  Nov 18 '13 at 12:16
  • 1
    Then you'd need to pass it within the callback. Either way, you're going to need to wait for the result to come back from the `$.ajax()` call. – ahren Nov 18 '13 at 12:17
  • Sorry to ask no of stupid questions, but if I do alert(count) inside the callback, I get the value, & if i assign it to some variable it still says undefined. Why so? I guess It has already calculated the value till then. –  Nov 18 '13 at 12:20
  • 1
    Because you're accessing that variable *before* it gets defined. Which is why you need to run the rest of your code within the callback. – ahren Nov 18 '13 at 12:21
  • Ohh, Ok. i got it now. –  Nov 18 '13 at 12:21
  • @user2614405 if you had already seen the other question and its answers, you should mention this in the question, as well as why it didn't help you. Also, if you had already seen the other question and its answers, I am surprised that you still thought your code would work. – John Dvorak Nov 19 '13 at 16:02
  • How can i make the value of count be returned to a variable like var results = getMessageCount(function(count){ return count; }); – devdar Apr 22 '14 at 18:46
0

use a callback:

call function like:

getMessageCount(function(result) {
//result is what you put in the callback. Count in your case
});

and the other like:

function getMessageCount(callback) {
    var count;
    $.ajax({
        type: "POST",
        url: "http://localhost:43390" + "/services/DiscussionWidgetService.asmx/GetMessageCount",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (data) {                            
            count = data.d;
            if (callback) {
             callback(count);
            }
        } //success
    });

}
CaptainCarl
  • 3,411
  • 6
  • 38
  • 71
0

Why you don't just pass it to a function?

function getMessageCount() {
  var count;
  $.ajax({
    type: "POST",
    url: "http://localhost:43390" + "/services/DiscussionWidgetService.asmx/GetMessageCount",
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function (data) {                            
       count = data.d;
       countMessages(count);

    } //success
   });
 }

function countMessages(counted) {var counted = counted; console.log(counted);}
MentalRay
  • 334
  • 1
  • 6
0
function ajax_call(url,data){
      return $.ajax({ type: "POST",
        url: url,
        data: data,
        async:false,
        success: function(status){
        }
    }).responseText;
}

Now you will get the response text from server side via ajax call

Shyam
  • 280
  • 1
  • 6
  • 17
Krishna
  • 9
  • 3