tags:

views:

57

answers:

3

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.

A: 

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);
    }
});
James Wiseman
If I can see a page's source code alerted, the ajax call worked. If I can't, it failed.
Delirium tremens
I updated the question. Everything changed. Please, come back!
Delirium tremens
I'm even less sure what you want from the edited post. Have you tried adding the error function as I stipulated above. I have changed my code to incorporate yours
James Wiseman
+1  A: 

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.

Brandon H
+1  A: 

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.

Scott