0

I have a following piece of javaScript code:

  var ws_path = "x";
 $.get('ws.config', function(data) {

      ws_path = data;
      alert(ws_path); //alert 1
 }, 
'text');

 alert(ws_path); // alert 2



  // output = alert 1 = value of data
   //         alert 2 = x

I have a confusion' why it is behaving like this?

pointer
  • 315
  • 1
  • 2
  • 18

3 Answers3

3

It is because alert(ws_path); gets executed before the content is get from server for ws.config file. You need to write the code in success function of get to ensure that variable is modified after get request.

jQuery.get

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
1

The second alert is fired before the $.get request is completed.

Cjmarkham
  • 9,484
  • 5
  • 48
  • 81
0

The important point here is:

$.get('ws.config' ....

is a kind of ajax call and it takes some time to get the actual value from the server, and that anonymous function there is a callback function which gets called when the ajax call receives the response.

Here in your code if you want to have a ordered scenario you can do this:

var ws_path = "x";
$.get('ws.config', function(data) {
    ws_path = data;
    alert(ws_path);
    continueScenario();
}, 'text');

function continueScenario(){
    alert(ws_path);
}
Mehran Hatami
  • 12,723
  • 6
  • 28
  • 35