NodeJS XMLHttpRequest response - javascript

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();

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);

Related

Perform $.getJSON without using JQuery [duplicate]

This question already has answers here:
How can I make an AJAX call without jQuery?
(24 answers)
Closed 6 years ago.
How do I get country code using javascript only, I am not allowed to use jQuery.
I have seen some sites like http://ipinfo.io , but all examples uses JQuery getJson, can I implement the same method :
var country_code = null;
$.getJSON('http://ipinfo.io/' + userip, function(data){
country_code = data.country;
alert(country_code);
});
I tried the following, but it returns a page instead:
var request = new XMLHttpRequest();
request.onload = function(elements) { console.log(elements); };
request.open("get", "http://ipinfo.io", true);
request.send();
Working example:
var someIp = '8.8.8.8';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
else if (xmlhttp.status == 400) {
alert('There was an error 400');
}
else {
alert('something else other than 200 was returned');
}
}
};
xmlhttp.open("GET", "//ipinfo.io/"+someIp+"/json", true);
xmlhttp.send();
<div id="myDiv">
pending
</div>
The ipinfo.io service returns JSON format only when proper header requesting JSON is attached. But it can be specified easily also with the /json directly in the requesting url.

Get JSON from local JavaScript

good afternoon. I'm developing an app that can get a JSON from local (manifest.json). I want to get this file from JavaScript and then read it. But I have a problem, I cant call this file. How can I?
var urlJSON = new XMLHttpRequest("manifes.json").toString;
var dataJSON = JSON.parse(urlJSON);
alert(dataJSON.name);
var xmlhttp = new XMLHttpRequest();
var url = 'manifest.json';
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log(JSON.parse(xmlhttp.responseText));
}
if (xmlhttp.status == 404) {}
};
xmlhttp.open('GET', url, true);
xmlhttp.send();
Or run chrome with arguments --allow-file-access-from-files
Or download and create server for your app

Get http.post in javascript then send a response

There's plenty of ways to do this in php, but I'm not a serverside, so is there a way to do this in pure JS?
Pure JS? Yes, but only on the server (the specifics would depend on which SSJS implementation you use, Express + NodeJS is popular at present).
You can't receive a POST request on the client. The client makes the request. The server makes the response. That is how HTTP works.
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "gethint.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
See more

How can I access to the serverside php from javascript?

I set some variables in serverside through PHP
$LGD_AMOUNT = ""; //Amount is for the price that customer purchases
$LGD_BUYER = "";//Buyer collect name of the customer
And I store these in $payReqMap
$payReqMap['LGD_AMOUNT'] = $LGD_AMOUNT;
$payReqMap['LGD_BUYER'] = $LGD_BUYER;
what I want to do is before I send these to the server side, in <script> part, I want to give them values. Is there any method that I can call these stored variables in <script> part?
This is a start point to use Ajax using pure Javascript;
function getxmlhttp (){
//Create a boolean variable to check for a valid Microsoft active x instance.
var xmlhttp = false;
//Check if we are using internet explorer.
try {
//If the javascript version is greater than 5.
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
//If not, then use the older active x object.
try {
//If we are using internet explorer.
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E) {
//Else we must be using a non-internet explorer browser.
xmlhttp = false;
}
}
// If not using IE, create a
// JavaScript instance of the object.
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}//Function getxmlhttp()
//Function to process an XMLHttpRequest.
function processajax (serverPage, obj, getOrPost, str){
//Get an XMLHttpRequest object for use.
xmlhttp = getxmlhttp ();
if (getOrPost == "get"){
xmlhttp.open("GET", serverPage);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
obj.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(null);
}
else {
xmlhttp.open("POST", serverPage, true);
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
obj.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(str);
}
}

Javascript only execute the last function called

I want my page to execute the same function 3 times, calling for 3 different things each time.
The code is currently
<script>
ajaxGet('/goget.php?name='+edit.dep.value, 'dep_result');
ajaxGet('/goget.php?name='+edit.arr.value, 'arr_result');
ajaxGet('/goget.php?type='+edit.reg.value, 'reg_result');
</script>
But it only executes the last call. Why?
Javascript:
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function ajaxGet(ajaxLoadData, changeToID) {
if(XMLHttpRequestObject) {
var obj = document.getElementById(changeToID);
XMLHttpRequestObject.open("GET", ajaxLoadData);
XMLHttpRequestObject.onreadystatechange = function() {
if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
}
You'll want to have each call to ajaxGet create its own XMLHttpRequest.
An XMLHttpRequest can only handle 1 request at a time. And, since they'll be making the request asynchronously, they'll be processing in parallel rather than sequentially.
function ajaxGet(ajaxLoadData, changeToID) {
var obj = document.getElementById(changeToID);
var xhr = new XMLHttpRequest();
xhr.open("GET", ajaxLoadData);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
obj.innerHTML = xhr.responseText;
}
};
xhr.send(null);
}
Granted, browsers generally limit requests to only a few at a time (usually 2), queuing any additional. But your code shouldn't count on that.
Side note: Unless you need to support IE6 or older, you shouldn't need to fallback to ActiveXObject.
You need to change your ajaxGet() method to instantiate a new XMLHttpRequest object at every call. Since, you're using the same XMLHttpRequest every new request is overwriting the previous one.
Hence, you're getting the results returned by the last method call only.
function getXHRObj() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
function ajaxGet(ajaxLoadData, changeToID) {
var XMLHttpRequestObject = getXHRObj();
var obj = document.getElementById(changeToID);
XMLHttpRequestObject.open("GET", ajaxLoadData);
XMLHttpRequestObject.onreadystatechange = function() {
if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}

Categories

Resources