/    Sign up×
Community /Pin to ProfileBookmark

Question for the AJAX knowledgeable.

I have two questions about the use of an AJAX function.
I am using the following function I found on a forum, mostly WITHOUT problems:

[code=php]
// ReadFile.js
function getFile(filename) {
oxmlhttp = null;
try {
oxmlhttp = new XMLHttpRequest();
oxmlhttp.overrideMimeType(“text/xml”);
}
catch(e) {
try { oxmlhttp = new ActiveXObject(“Msxml2.XMLHTTP”); }
catch(e) { return null; }
}
if(!oxmlhttp) return null;
try {
oxmlhttp.open(“GET”,filename,false);
oxmlhttp.send(null);
}
catch(e) { return null; }
return oxmlhttp.responseText;
}
[/code]

The error looks like this, but will change depending upon the first line in the text file that I’m trying to read.

[quote]

Error: syntax error
Source File: [url]http://www.nova.edu/optometry/411/NewSced/DBI/Summer07.txt[/url]
Line: 1, Column: 1
Source Code:
post time|user|{|^

[/quote]

It seems to work fine but occasionally (not always) I get an error in the JS error console using FireFox. It gives an error about the TEXT file that I am loading using the routine.

It reports the error, but it does not stop the function from completing nor does it appear to effect the results of the read operation.

So here are my questions:
1. Is there a reason why I’m getting the errors reported but the function appears to work fine and is there a change to the routine I should make to eliminate the error report in the JS console?
2. Will I cause any problem if I repeat the call at a later time in the same script?

to post a comment
JavaScript

14 Comments(s)

Copy linkTweet thisAlerts:
@rootApr 24.2007 — something calle .onreadystatechange is a state change listener, it fires on every state change that takes place in the oxmlhttp object.

  • 1. create an http object

    2a. open a request

    2b. apply any overrides

  • 3. apply the event listener to call a handler function.

  • 4. send the request


  • the event handler is a function to check the ready state of the incoming data, eg when the readyState is 4, the file has loaded.

    function handler(){

    if(oxmlhttp.readyState==4) alert(oxmlhttp.responseText);

    }

    ... for example.

    if you want to load an XML file, use the XML response handler, you have responseBody, responseText & responseXML
    Copy linkTweet thisAlerts:
    @JMRKERauthorApr 25.2007 — To '.'

    Thanks for the response.

    While I'm not sure I understand all that you sent, at least it will give me some words to use in a search for more information.

    Since I get an error in the JS console, but the script where I use the information obtained seems to complete and operate as expected, do I need to worry?

    In other words is it safe to ignore the JS console in this case?

    I am using the 'ReadFile()' routine in an HTML/JS program, but your comments seem to be related to XML.


    Is this why I'm getting the error messages sometimes and not other times?


    Is it related to the 'readyState' you mentioned and the error I'm getting is just a response that the information is not totally ready when I call upon it in the 'ReadFile()' function?

    I appreciate your reply. Do you have a favorite resource to look at that might not be to far beyond my comprehension so that I don't ask as many questions in the future?

    Thanks again!
    Copy linkTweet thisAlerts:
    @rootApr 25.2007 — The data has to go through a number of states before it is ready to use.

    the states are 0 to 4, so when the readyState is 4, the data has loaded and complete.

    if you try and bypass the readystate handeler, your responseText or body or XML wont be complete or ready to use because you have grabbed the current state of the response.
    Copy linkTweet thisAlerts:
    @rootApr 25.2007 — What your script is doing is sending the request and then grabbing the answer before it has loaded.
    Copy linkTweet thisAlerts:
    @JMRKERauthorApr 25.2007 — '.': Thanks for the extra responses.

    OK, now I may have what I hope is a better question.

    In the last line of the 'ReadFile.js' of the first post I tried the following:
    [code=php]
    ...
    catch(e) { return null; }

    if ((oxmlhttp.status == 200) && (oxmlhttp.readState == 4)) {
    return oxmlhttp.responseText;
    } else { return 'Not Ready Yet!'; }

    }
    [/code]

    According to a 'google' search these are the expected values to have when the file is read correctly.

    But instead of the file contents which I correctly received before,

    now I only get the 'Not Ready Yet!' message.

    Question: What is the correct method(s) to test the 'status' and the 'readyState' variables in the called function 'getFile(filename)'?
    Copy linkTweet thisAlerts:
    @rootApr 30.2007 — exactly that, you dont want to return anything until the response so ommit the else { return 'Not Ready Yet!'; }portion and nothing will return until the file has loaded. I am assuming that no other returns are left other than return oxmlhttp.responseText; which is the condition that you need to return the data.
    Copy linkTweet thisAlerts:
    @JMRKERauthorApr 30.2007 — So now my understanding is this:

    The event is continuously sampled (somehow or somewhere)

    until the status == 200 and readyState == 4, at which time the responseText is returned.

    If the conditions are not met (status and readyState), then nothing is returned from the call.


    If this is so, where does the re-call of my function to get the responseText returned occur

    or is this taken care of somehow by the event(e) function not having been satisfied?

    Do I ever need to view the status and readyState as separate function,

    as for example in a progress bar of readyState from 0 to 4?

    Sorry for my ignorance, I'm still trying to understand how it works!

    Do I need to do more advanced study on what an event() does in AJAX?
    Copy linkTweet thisAlerts:
    @rootApr 30.2007 — each time the even listener "onreadystatechange" is triggered as the data starts loading from the server, it goes through 5 states.
    0 (Uninitialized) The object has been created, but not initialized (the open method has not been called).

    1 (Open) The object has been created, but the send method has not been called.

    2 (Sent) The send method has been called, but the status and headers are not yet available.

    3 (Receiving) Some data has been received. Calling the responseBody and responseText properties at this state to obtain partial results will return an error, because status and response headers are not fully available.

    4 (Loaded) All the data has been received, and the complete data is available. [/quote]

    So when the server is reporting 200 as all OK, and the readyState of the object is 4 as Loaded, you want to return your data but for everything else, you want to ignor any returns.
    Copy linkTweet thisAlerts:
    @JMRKERauthorMay 01.2007 — To .

    I sure hate to be a pest, but here's what I've done.

    I removed the "else' part of the 'if' statement to have:
    [code=php]
    ...
    catch(e) { return null; }

    if ((oxmlhttp.status == 200) && (oxmlhttp.readState == 4)) {
    return oxmlhttp.responseText;
    }
    }
    [/code]

    and I get a constant error that the text file has not been read completely.

    When I remove the 'if', leaving only the 'return'

    I can read the file (appears complete), but I continue to get the original JS console warning error.


    Now I'm back to the original post code.

    So, although I now understand the function better, I still have the original post problem. Is there a solution that I'm missing to avoid the warning error in the reading of text file line #1 altogether?

    Thanks for trying to enlighten me.
    Copy linkTweet thisAlerts:
    @rootMay 01.2007 — it makes no sense, it may help if you post the entire script [b]AS[/b] you have it now, something is returning before your document has loaded.

    the process as you will have seen goes through various "readystates" that you can test for :
    function myHandler(){
    if(httpobject.readyState == 4) myResponse = httpobject.responseText;
    }
    would be called eash ready state change detected, tested and if condition is met, the response is dumpred into a variable called myResponse.
    Copy linkTweet thisAlerts:
    @JMRKERauthorMay 01.2007 — Thank you '.' for all your assistance.

    Here is what I have:

    ReadFile.js is a separate file that I have merged into ReadFile.html below:

    ReadFile.html
    [code=php]
    <html>
    <head>
    <title>File Reader</title>
    <script type="text/javascript">

    function getFile(filename) {
    oxmlhttp = null;
    try {
    oxmlhttp = new XMLHttpRequest();
    oxmlhttp.overrideMimeType("text/xml");
    }
    catch(e) {
    try { oxmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
    catch(e) { return null; }
    }
    if(!oxmlhttp) return null;
    try {
    oxmlhttp.open("GET",filename,false);
    oxmlhttp.send(null);
    }
    catch(e) { return null; }
    return oxmlhttp.responseText;
    }

    </script>
    </head>
    <body>
    File Reader<p />
    <button onClick="document.getElementById('Info').value=getFile('ReadFile.txt')">
    ReadFile.txt</button>
    <br />
    <textarea id="Info" rows="20" cols="60"></textarea>

    </body>
    </html>
    [/code]


    Sample data text file
    [code=php]
    post time|user|{| StartSemDate|5/14/2007|MaxWeeks|12|}
    post time|user|{|
    Semester|
    ||||||||||||||||||
    |||||Holiday||||||Holiday||||||Holiday|
    Holiday||||||Holiday||||||Holiday||||||
    ||||||||||||||||||
    ||||||||||||||||||
    ||||||||||||||||||
    ||||||||||||||||||
    ||Holiday||||||Holiday||||||Holiday||||
    ||||||||||||||||||
    ||||||||||||||||||
    ||||||||||||||||||
    ||||||||||||||||||
    }
    04/27/07 14:48|Chennel|{|
    Rumsey|
    |NMB_Peds|Holiday|||||NMB_Peds||Holiday||||NMB_Peds|Holiday||||
    |NMB_Peds||||Holiday||NMB_Peds||||Holiday||NMB_Peds||||Holiday|
    Holiday|NMB_Peds|||||Holiday|NMB_Peds|||||Holiday|NMB_Peds|||||
    |NMB_Peds||||||NMB_Peds||||||NMB_Peds|||||
    |NMB_Peds||||||NMB_Peds||||||NMB_Peds|||||
    |NMB_Peds||||||NMB_Peds||||||NMB_Peds|||||
    |NMB_Peds||||||NMB_Peds||||||NMB_Peds|||||
    |NMB_Peds|Holiday|||||NMB_Peds|Holiday|||||NMB_Peds|Holiday||||
    |NMB_Peds||||||NMB_Peds||||||NMB_Peds|||||
    |NMB_Peds||||||NMB_Peds||||||NMB_Peds|||||
    |NMB_Peds||||||NMB_Peds||||||NMB_Peds|||||
    |NMB_Peds||||||NMB_Peds||||||NMB_Peds|||||
    |}
    [/code]


    To repeat my problem.


    Intermittently I get a JS console error that there is a syntax error

    in reading the first line of the text file, although the file does appear

    to be read correctly to completion. I wish I could say that it happen

    every time I tried to read the file, for then it would be easier to solve.

    I'm just trying to figure out where the problem is and my first assumption

    was that the 'readyState' was not 'ready'.
    Copy linkTweet thisAlerts:
    @rootMay 03.2007 — using the example off the jibbering website, <i>
    </i>function createHttpRequestObject(){
    var xmlhttp=false;
    try {
    xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
    try {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (E) {
    xmlhttp = false;
    }
    }
    if (!xmlhttp &amp;&amp; typeof XMLHttpRequest!='undefined') {
    try {
    xmlhttp = new XMLHttpRequest();
    } catch (e) {
    xmlhttp=false;
    }
    }
    if (!xmlhttp &amp;&amp; window.createRequest) {
    try {
    xmlhttp = window.createRequest();
    } catch (e) {
    xmlhttp=false;
    }
    }
    return xmlhttp;
    }
    has been changed to a function, each time it is called it will return a new object.

    use a request routine like...
    <i>
    </i>function getData(url)
    {
    http=createHttpRequestObject();
    if(http)
    {
    http.open("GET",url,true);
    http.onreadystatechange = function()
    {
    if(http.readyState == 4)
    {
    if(http.status == 200) response = http.responseText;
    }
    }
    http.send(null);
    }
    }
    The examples above should guide you.
    Copy linkTweet thisAlerts:
    @JMRKERauthorMay 04.2007 — Thanks for the code.

    I'll give it a try.

    '.', ... I appreciate the tolerance for the questions presented.

    BTW: What is 'the jibbering website' referring to?
    Copy linkTweet thisAlerts:
    @rootMay 04.2007 — it is a link in someones signature in a post I found, the url is: http://www.jibbering.com/2002/4/httprequest.html
    ×

    Success!

    Help @JMRKER spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 4.29,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,

    tipper: @Samric24,
    tipped: article
    amount: 1000 SATS,
    )...