1

I am having trouble making changes to any variable inside the AJAX function.

If I have a variable outside lets say

var myName = "My name is Kenny";

and inside the AJAX function I do myName.replace("Kenny", "Earl");

When I do console.log(myName) after the AJAX function I get "My name is Kenny" as if nothing happened.

Here is an example:

var actorId;
var castListUrl = 'http://api.themoviedb.org/3/person/id/movie_credits?api_key=###';
//start ajax request
$.ajax({
    url: "http://api.themoviedb.org/3/search/person?api_key=###&query=" + actorsName,
    //force to handle it as text
    dataType: "text",
    success: function (data) {
        //data downloaded so we call parseJSON function 
        //and pass downloaded data
        var json = $.parseJSON(data);
        actorId = json.results[0].id;

        castListUrl = castListUrl.replace("id", "1245");
        console.log(castListUrl); // This returns 'http://api.themoviedb.org/3/person/1245/     movie_credits?api_key=###' with **ID** being changed

        //now json variable contains data in json format
        //let's display a few items
        $('#results').html('The actors name is ' + json.results[0].id);
    }
});
console.log(castListUrl); // This returns 'http://api.themoviedb.org/3/person/id/movie_credits?api_key=###' without **ID** being changed

I have been reading about jQuery scopes and I cannot tell what I'm doing wrong.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Kenneth
  • 137
  • 8
  • 1
    AJAX is *asynchronous*. It will run *after* your other code completes (possibly quite a long time after, if the download takes a while). You need to restructure your code to be event-driven. – Dave Nov 30 '13 at 16:18

1 Answers1

3

AJAX requests are asynchronous: once you have made the request your code will continue to execute without waiting for the response. Your response callback, where you update the variable, will be called when the response arrives.

That means that console.log is executed before your AJAX response callback. If you move it into the callback you will see the updated value.

joews
  • 29,767
  • 10
  • 79
  • 91