aliassce
aliassce

Reputation: 1197

JQuery wait for Ajax Result

I have a function making Asp.Net Web service calls by taking method name and data as parameters. There is no problem sending data to service. But my retun value is undefined

function ServiceCommand(method, mdata) {
            $.ajax({
                url: "Service1.asmx/" + method,
                type: "POST",
                dataType: "json",
                data: mdata,
                contentType: "application/json; charset=utf-8",
                success: function (msg) {
                    return msg;
                },
                error: function (e) {
                    return "error";
                }
            });
        }

function Insert()
{
var Msg = ServiceCommand("HelloWorld", "{pwd:'1234',txt:'SomeText'}");
alert(Msg);// undefined

}

How can I make ServiceCommand function wait until a response comes? I'm using JQuery 1.9 (async:false doesn't work) I saw some solutions advising usage of $.When but I couln't figure out how to use here.

Upvotes: 1

Views: 1870

Answers (2)

rhoadsce
rhoadsce

Reputation: 278

A simple way to do this without using promises (.when) would be to pass a callback function into ServiceCommand as a third parameter. This function would do whatever it is that you need to do with the response from the ajax call.

function ServiceCommand(method, mdata, onSuccessCallback) {
        $.ajax({
            url: "Service1.asmx/" + method,
            type: "POST",
            dataType: "json",
            data: mdata,
            contentType: "application/json; charset=utf-8",
            success: function (msg) {
                if (onSuccessCallback !== undefined) {
                    onSuccessCallback(msg);
                }
            },
            error: function (e) {
                return "error";
            }
        });
    }

function Insert()
{
    var Msg = ServiceCommand("HelloWorld", "{pwd:'1234',txt:'SomeText'}", onSuccess);
    alert(Msg);
}
function onSuccess(msg)
{
    alert(msg);
}

Upvotes: 2

NullPointerException
NullPointerException

Reputation: 3814

use async=false;

$.ajax({
   url: myUrl,
   dataType: 'json',
   async: false

Upvotes: 1

Related Questions