alexandre1985 alexandre1985 - 4 years ago 264
Node.js Question

NodeJS XMLHttpRequest response

I'm making and app and I need do get the number of verses of a chapter of the bible.

I'm getting the info from http://www.kingjamesbibleonline.org/

In order to do that I am making an XMLHttpRequest to send to the server from the function

getVerses()
from the site.

The problem that I am facing is that I'm not getting a .responseText from the XMLHttpRequest. When I use firebug and call that function, in the Network tab > Response tab I get nothing but on Network tab > Preview I get the answer.

Where is this answer coming from and what is the variable that has this value?

My node code is as follows:

let XMLHttpRequest2 = require("xmlhttprequest").XMLHttpRequest;

function getVerses() {
let xmlhttp = new XMLHttpRequest2(); //: new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == xmlhttp.DONE ) {
if(xmlhttp.status == 200){
console.log(xmlhttp.responseText);
}
else if(xmlhttp.status == 400) { }
else { }
}
}
xmlhttp.open("POST", "http://www.kingjamesbibleonline.org/ajax.php", true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send('callFunc=getMaxVerseForChapter&book='+'"Genesis"'+'&chapter='+'"2"');
}

getVerses();

Answer Source

Apparently the server is very strict and it expects the header to be called Content-Type and not Content-type. Some kind of poorly written stuff obviously (in PHP). Also get rid of the double quotes around the values you are sending.

Here you go:

let XMLHttpRequest2 = require("xmlhttprequest").XMLHttpRequest;

function getVerses() {
    let xmlhttp = new XMLHttpRequest2(); //: new ActiveXObject("Microsoft.XMLHTTP");
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == xmlhttp.DONE ) {
            if(xmlhttp.status == 200){
                console.log(xmlhttp.responseText);
            }
            else if(xmlhttp.status == 400) { }
            else { }
        }
    }
    xmlhttp.open("POST", "http://www.kingjamesbibleonline.org/ajax.php", true);
    xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    xmlhttp.send('callFunc=getMaxVerseForChapter&book=' + 'Genesis' + '&chapter=' + '2');
}

getVerses();

and since you are hardcoding the values, you don't really need string concatenation:

xmlhttp.send('callFunc=getMaxVerseForChapter&book=Genesis&chapter=2);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download