Not with an asynchronous request, which is the normal kind of ajax request and the preferred kind. That's because load
returns before you get your reply from the server, so obviously it can't return the msg
. Instead, have load
accept a callback:
load(function(msg) {
// Use msg here
});
function load(callback)
{
$.ajax({
type: "POST",
url: "myPage.aspx/MyMethod",
data: jsonText,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Call our callback with the message
callback(msg);
},
failure: function () {
// Call our callback with an indication things failed
callback(null); // Or however you want to flag failure
}
});
}
If absolutely unavoidable, you could use a synchronous request by setting async: false
in your $.ajax
options (that's a link to the docs), then do it like this:
var msg = load();
function load(callback)
{
var result;
$.ajax({
type: "POST",
url: "myPage.aspx/MyMethod",
data: jsonText,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (msg) {
// Set the `result` value here. We can't *return* it
// here because, of course, that would just return it
// from our `success` function.
result = msg;
},
failure: function () {
result = null; // Or however you want to flag failure
}
});
// Because we've made the request synchronous, we won't get here
// until the ajax call is complete and `result` has been set by
// the callbacks above; we can now return it.
return result;
}
But synchronous requests make for a poor user experience and, moreover, are almost never necessary, so should be avoided as much as possible.