I have the following code, which displays 2 alerts:
function GetDepartment(){
var dept;
$.ajax({
type: 'POST',
url: 'return_string.asmx/GetDepartment',
data: '{}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function( department ) {
if( department.d[0] ) {
dept = department.d[0].code;
alert( dept );
} else {
alert ( "null" );
}
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message) ;
}
});
return dept;
}
alert( GetDepartment() );
The first alert displays undefined and the second alert displays MKTG
Why is the first alert displaying undefined and how do I get both to display MKTG?
It will work the way you want it to only if your AJAX call is synchronous. For this you can specify
async: falsein your AJAX call.Even better, restructure your app so that the AJAX call can proceed asynchronously without blocking the UI thread and can issue a callback to continue your app-specific processes.
ie. something like: