33

Possible Duplicate:
How do I return the response from an asynchronous call?

I am using Jquery Ajax to call a service to update a value.

function ChangePurpose(Vid, PurId) {
    var Success = false;
    $.ajax({
        type: "POST",
        url: "CHService.asmx/SavePurpose",
        dataType: "text",
        data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            Success = true;//doesn't go here
        },
        error: function (textStatus, errorThrown) {
            Success = false;//doesn't go here
        }

    });
    //done after here
    return Success;
}

and Service:

[WebMethod]
public string SavePurpose(int Vid, int PurpId)
{
    try 
    {
        CHData.UpdatePurpose(Vid, PurpId);
        //List<IDName> abc = new List<IDName>();
        //abc.Add(new IDName { Name=1, value="Success" });
        return "Success";
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message);
    }
}

the service is being called Successfully from the AJAX. Value is also being Changed. But after the Service, success: or error: functions are not being called, in this case success should have been called but it is not working.

I used firebug and found that, the success or error functions are being skipped and goes directly to return Success;

Can't seem to find what's the problem with the code.

Update: adding async: false fixed the problem

Cœur
  • 37,241
  • 25
  • 195
  • 267
Ruchan
  • 3,124
  • 7
  • 36
  • 72
  • 4
    That's how Ajax works... welcome to async! If it comforts you: It feels like at least three people ask this question *every day*. – Felix Kling Jan 23 '13 at 09:07
  • You don't know how to correctly inspect the code. A breakpoint may have been more helpful since AJAX is asynchronous – Alexander Jan 23 '13 at 09:08
  • Did you put an alert before Success = true – muthu Jan 23 '13 at 09:09
  • 1
    Doubt anyone's coming back here, but what's better about this "duplicate" is that the words it uses in the title are I think a lot more likely to match the search of someone having this problem. In the case of the other answer you would have to specifically already understand the answer somewhat to generate a search that would lead you to that page. Of course, this page leads you to that page, but still. – Raydot Dec 09 '14 at 00:01
  • Try to use following: ``` complete: function (xhr, status) { alert("Called when Ajax request completes"); } ``` – Akshay Anand Aug 23 '18 at 21:56

2 Answers2

30

change your code to:

function ChangePurpose(Vid, PurId) {
    var Success = false;
    $.ajax({
        type: "POST",
        url: "CHService.asmx/SavePurpose",
        dataType: "text",
        async: false,
        data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            Success = true;
        },
        error: function (textStatus, errorThrown) {
            Success = false;
        }
    });
    //done after here
    return Success;
} 

You can only return the values from a synchronous function. Otherwise you will have to make a callback.

So I just added async:false, to your ajax call

Update:

jquery ajax calls are asynchronous by default. So success & error functions will be called when the ajax load is complete. But your return statement will be executed just after the ajax call is started.

A better approach will be:

     // callbackfn is the pointer to any function that needs to be called
     function ChangePurpose(Vid, PurId, callbackfn) {
        var Success = false;
        $.ajax({
            type: "POST",
            url: "CHService.asmx/SavePurpose",
            dataType: "text",
            data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                callbackfn(data)
            },
            error: function (textStatus, errorThrown) {
                callbackfn("Error getting the data")
            }
        });
     } 

     function Callback(data)
     {
        alert(data);
     }

and call the ajax as:

 // Callback is the callback-function that needs to be called when asynchronous call is complete
 ChangePurpose(Vid, PurId, Callback);
Cœur
  • 37,241
  • 25
  • 195
  • 267
Wolf
  • 2,150
  • 1
  • 15
  • 11
  • That... that. worked! Thanks so much. But how can you explain it? – Ruchan Jan 23 '13 at 09:15
  • 2
    @Ruchan: Read the question in linked to in my first comment. It explains it and also why using this solution (`async:false`) is not good. – Felix Kling Jan 23 '13 at 09:21
  • i understand it(Felix Kling) but what work around would be there? I need to display message there. – Ruchan Jan 23 '13 at 09:25
  • 2
    @Felix Kling: you are correct. Updated my answer. Ruchan: You can use async:false, if you need synchronous calls (in cases like, your code will not continue without the ajax script etc) – Wolf Jan 23 '13 at 09:33
  • Somebody down-voted me for nothing? – Wolf Jan 23 '13 at 09:37
  • @Wolf shouldn't the `function Callback(data)` be `function ChangePurpose(data)`? – Ruchan Jan 23 '13 at 09:51
  • http://jsbin.com/abimob/348/edit i looked up this... and your update is quite confusing @Wolf – Ruchan Jan 23 '13 at 09:57
  • @Ruchan: What exactly are you having trouble understanding? What callbacks are and how they work? – Felix Kling Jan 23 '13 at 09:59
  • @FelixKling I understood what callbacks are, but still cant understand how to define them... Looking up some examples right now... – Ruchan Jan 23 '13 at 10:13
  • @Ruchan: There is an example in this answer and in mine (link). A callback is just a function that is passed to another function. You don't have to define it in any special way. The *other* function just has to expect a callback and call it eventually. – Felix Kling Jan 23 '13 at 10:17
  • @Ruchan: did you try the updated code? – Wolf Jan 23 '13 at 10:50
  • @FelixKling wolf's update is not working. can you make it right? – Ruchan Jan 23 '13 at 10:51
  • What is the error you are getting? I just typed the code. Didn't try it. But doesn't seems like having an error. – Wolf Jan 23 '13 at 10:52
  • It didnt respond.. i looked up in firebug the code got greyed... meaning no breakpoint or something – Ruchan Jan 23 '13 at 10:59
  • Sorry i had some typing mistakes... it is working Correctly now \/ Thanks very much – Ruchan Jan 23 '13 at 11:10
  • thanks a ton @Wolf. It solved my problem :) – Shraddha Banerjee Mar 22 '18 at 12:03
11

Try to encapsulate the ajax call into a function and set the async option to false. Note that this option is deprecated since jQuery 1.8.

function foo() {
    var myajax = $.ajax({
        type: "POST",
        url: "CHService.asmx/SavePurpose",
        dataType: "text",
        data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
        contentType: "application/json; charset=utf-8",
        async: false, //add this
    });
    return myajax.responseText;
}

You can do this also:

$.ajax({
    type: "POST",
    url: "CHService.asmx/SavePurpose",
    dataType: "text",
    data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
    contentType: "application/json; charset=utf-8",
    async: false, //add this
}).done(function ( data ) {
        Success = true;
}).fail(function ( data ) {
       Success = false;
});

You can read more about the jqXHR jQuery Object

Tomas Ramirez Sarduy
  • 17,294
  • 8
  • 69
  • 85