Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XMLHttprequest.send(null) is crashing my code

I'm currently writing a search function using JavaScript.

However, when I attempt to test my creation, I find that it stops about halfway through for no discernible reason.

Below is my code:

document.getElementById("test").innerHTML = "";
var Connect = new XMLHttpRequest();
Connect.open("GET", "xmlTest.xml", false);
document.getElementById("test").innerHTML = "1";
Connect.send(null);
document.getElementById("test").innerHTML = "2";
var docX = Connect.responseXML;
var linjer = docX.getElementsByTagName("linjer");

The first line is there to clear a potential error message from earlier in the code. Then I attempt to open up an XML file, as I need to read from it.

As you can see, I've entered two debug statements there; they will print 1 or 2 depending on how far I get in the code.

Using this, I've found that it stops exactly on the Connect.send(null); statement (as 1 gets printed, but 2 never does), but I can't figure out why. Google says that it might be that chrome can't access local files, but when I found a way to allow Chrome to do this, it still did not work.

What am I doing wrong?

like image 793
TheJack38 Avatar asked Nov 09 '22 02:11

TheJack38


1 Answers

This might be a synchronous issue that requires a response that your code simply is not getting.

Try using an async call instead:

Connect.open("GET", "xmlTest.xml", true);

Also make sure to setup proper callbacks since you'll be using async here now instead of synchronous code, like so:

// Global variable scope
var docX;
var linjer;

// Define your get function
getDoc = function(url, cbFunc) {

    var Connect = new XMLHttpRequest();

    // Perform actions after request is sent
    // You'll insert your callback here
    Connect.onreadystatechange = function() {
        // 4 means request finished and response is ready
        if ( Connect.readyState == 4 ) {
            // Here is where you do the callback
            cbFunc(Connect.responseXML);
        } 
    }; 

    // 'true' param means async, it is also the default
    Connect.open('GET', url, true);
    Connect.send();
}

// Define your callback function    
callbackFunction = function(responseXML) {
    // XML file can now be stored in the global variable
    window.docX = responseXML;
    window.linjer = window.docX.getElementsByTagName("linjer");
}

// And here is the call you make to do this
getDoc("xmlTest.xml", callbackFunction); 

For better understanding of all of this, do some research on scope, closures, callbacks, and async.

like image 144
rambossa Avatar answered Nov 14 '22 22:11

rambossa