Reputation: 4739
The code
uri = 'http://www.test.com/';
$.ajax({
url: uri,
success: function(msg){
sc.searchcontents = msg;
alert(sc.searchcontents);
}
});
alert(sc.searchcontents);
alerts undefined, then alerts the page's source code.
Upvotes: 0
Views: 92
Reputation:
The second alert box is being called before the ajax is done because the ajax call is async by default. Add the async: false clause and that should resolve your issue.
Upvotes: 1
Reputation: 30498
How are you determining that it works or fails?
What are the error messages you are getting?
Have you read the jQuery Ajax Documentation?
To help you deterine what is going on, try adding an error
function:
uri = 'http://www.test.com/';
$.ajax({
url: uri,
success: function(msg){
sc.searchcontents = msg;
alert(sc.searchcontents);
}
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
Upvotes: 0
Reputation: 3720
the success function of ajax runs after it loads. however, the javascript on your page will keep going while ajax loads its url. the alert you are seeing first is the one outside of your ajax call (undefined) and then the one within the ajax call (source code).
for testing, try putting a delay in the one at the end of your code sample. you'll see what i mean.
Upvotes: 1