-1
var myXML;
$.ajax({
  type:'GET',
  url:'http://localhost:8080/someCGIhere/',
  datatype:'xml',
  success: function(xml){
    console.log('Success!');
    myXML = $(xml).find('SomeThing').text();
    //1) Prints out the myXML value        
    console.log("myXML = " +myXML);
  }
});

//2) Prints out undefined
console.log('Result = '+myXML);

How come the response is not stored outside of success scope, considering it is assigning the value to a variable declared outside of its scope?

halfer
  • 19,824
  • 17
  • 99
  • 186
Cisum Inas
  • 11,552
  • 11
  • 40
  • 55
  • 6
    `$.ajax`make an async request so `//2` is executed before `//1` .You should be able to see `Result = undefined` before `Success!` in the console – Hacketo Aug 31 '15 at 14:26
  • I do see it in the console, now I understand! in my mind javascript had to wait for the call to finish before it could proceed sequentially in the code, thank you! @Hacketo – Cisum Inas Aug 31 '15 at 14:29
  • Sorry Hacketo, I did not see your comment before I answered – Ello Aug 31 '15 at 14:35

2 Answers2

2

The second console.log gets executed before the first one in the success function, since ajax is an asynchronous process. You either need to use a callback function to make sure the second console.log gets executed after the ajax call or you can use promises

Ello
  • 907
  • 1
  • 15
  • 33
1

Let's see what your code is doing.

  1. declare the variable myXML (=null)
  2. start the $.ajax request (and declare what to do if it - eventually, at some point in the future - finishes successfully)
  3. log the content of myXML

Note that unless the success callback is called before point 3. (which is extremely unlikely), myXML will still be null at that point.

In other words, when the callback is called, myXML shall be updated. Before that, it is what you declared it to be in point 1, i.e. null. The code does exactly what you asked it to do, but it's something else than what you wanted.

Piskvor left the building
  • 91,498
  • 46
  • 177
  • 222