0

Team, I want the browser to read a property file from server. So i am following Jquery/AJaX like below.

<script>
var properties = null;
$(document).ready(function(){
    $.ajax({url:"demo_test.txt",success:function(result){
    properties = result;
    //properties = $('#result').val()
    //jQuery.globalEval("var newVar = result;")
    document.write("inside " + properties);
}});
});
document.write("outside " + properties );
</script>

Here "inside " is properly printing the file chars. But " outside " is printing null for properties.

  1. Why?
  2. I am able to see "outside " output on the page; only if i comment "inside " line? Why so?
  3. How to get the jquery result for further processing on data?
  4. Can i have a property file (key=value) in the server and is there any facility offered by jquery/ajax similar to java.util.property :: getValue("key")? if the above is not possible; can i keep the property file as JSON or XML file and any utilities offered by Ajax to get value for a key??

Update:

I have made some research and updating the answer for Q4.
I am not sure how to read properties file, but i gave solution for xml/json file reading.

After changing Synchronous Ajax call like below

var properties = null;
   $.ajax({
   url : "demo_test.txt",
   async : false,
   success : function(result)
   {
       properties = result;
       document.write("inside " + properties);
    }
}); 

If the server side has a XML file below is the way to parse:

 <?xml version="1.0"?>
 <server>
    <name>velu</name>
 </server> 

if (window.DOMParser)
{
    parser=new DOMParser();
    xmlDoc=parser.parseFromString(property,"text/xml");
}
else // Internet Explorer
{
    xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async=false;
    xmlDoc.loadXML(property); 
} 
alert(xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue);


If you have json content on the server side then

{
"name":velu
}

var obj = JSON.parse(property);
alert(obj.name);  



Javascript style for accessing the file (Asynchronus)

var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{// listener
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    property = xmlhttp.responseText;
    }
}
xmlhttp.open("GET","demo_test.txt",true);
xmlhttp.send();
while (property != null) {
    alert(property); 
    break;
}
Kanagavelu Sugumar
  • 18,766
  • 20
  • 94
  • 101
  • 3
    Dude, AJAX is asynchronous, what do you expect? – A. Wolff May 23 '13 at 14:07
  • @roasted Thanks. But how does that matters here; here the output is behaving differently in the construcut. – Kanagavelu Sugumar May 23 '13 at 14:08
  • 2
    1-3: Ajax is asynchronous, you can't(shouldn't) access data from the request outside of the success callback. 4: i don't understand. Also, don't use document.write. There's only a handfull of edge cases where it makes sense to use document.write, and this isn't one of them. – Kevin B May 23 '13 at 14:08
  • Because the document.write line executes before the AJAX has returned the information. – Jay Blanchard May 23 '13 at 14:08
  • possible duplicate of [How to return AJAX response Text?](http://stackoverflow.com/questions/1225667/how-to-return-ajax-response-text) – Quentin May 23 '13 at 15:05

1 Answers1

4

You're using two bits of Javascript functionality that run in what's called an asynchronous manner: onready, and AJAX. That means you set them up, and the rest of your code after the setup continues to run until the necessary conditions are met to trigger the event. A single request can take a significant amount of time to complete, enough that thousands of lines of code or more can be run before a return is issued.

So here's what's happening in your script:

The first line is called and completed,

var properties = null;

Next, you tell your document to perform some code when it's ready and fully loaded:

$(document).ready(function(){...});

Your document isn't ready yet (we're still in the realm of run-right-away-code) so the next line executes,

document.write("outside " + properties );

properties is still null (the code inside of the .ready() function hasn't been called, yet).

Sometime later, the document is ready and the provided function is called,

function(){
    $.ajax({url:"demo_test.txt",success:function(result){
    properties = result;

    document.write("inside " + properties);
}});

In this function, you set up an AJAX request, which runs a function on completion,

$.ajax({url:"demo_test.txt",success:function(result){...}});

This request is also asynchronous, so the rest of your code will out while this request is processed and returned from the server. There are no other functional lines of your program after this, though, so sometime later, the function becomes the next thing called.

    properties = result;

    document.write("inside " + properties);

(I've removed the comments for readability)

properties is set to result and then printed out as a non-null value. This also explains why you probably saw the "outside" write displayed first, and the "inside" write displayed second, even though it appears "inside" should come first.

The best way to handle a situation like this, is to continue all of your code inside of the returned AJAX request, or make the request call another function that continues your code. That way you'll know that the request has already processed and that it's safe to continue:

var properties = null;
$.ajax({
    url : "demo_test.txt",
    success : function(result)
    {
        properties = result;
        document.write("inside " + properties);
        runTheRestOfMyCode();
    }
});

function runTheRestOfMyCode()
{
    document.write("outside " + properties );
}

Alternatively, you can set jQuery's async setting in the AJAX request to false. This will keep your code from progressing to the next line until the request is made and returned, but it will pause everything while it waits.

var properties = null;
$.ajax({
    url : "demo_test.txt",
    async : false,
    success : function(result)
    {
        properties = result;
        document.write("inside " + properties);
        runTheRestOfMyCode();
    }
});

document.write("outside " + properties );
Sandy Gifford
  • 7,219
  • 3
  • 35
  • 65
  • One question here. once i made async : false then i can runTheRestOfMyCode the execution will be normal (sequential) rit ..? No need to call runTheRestOfMyCode() inside the ajax rit?? – Kanagavelu Sugumar May 23 '13 at 16:01
  • 1
    Correct. If you're making a synchronous request by setting `async` to `false` then you don't need to house your code in a separate function. The advantage of using another function is that your code won't have to pause while the request is made, you can take care of other requests in the downtime. – Sandy Gifford May 23 '13 at 16:06