Perform $.getJSON without using JQuery [duplicate] - javascript

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.

Related

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

xmlhttp.open multiple XML files

How would I go about fetching multiple XML files? I tried creating an array but that only opens the last file, and as I understand it xmlhttp.open is supposed to cancel any previous send. I tried modifying this which was the closest thing I could find, but my JavaScript knowledge is a bit to limited to adapt it.
This is the basic code I'm using to get one XML file.
if (window.XMLHttpRequest)
{ xmlhttp=new XMLHttpRequest();
}
xmlhttp.open("GET","myfile.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var x=xmlDoc.getElementsByTagName("TAGNAME");
for (i=0;i<x.length;i++)
{ // Further parsing
}
Also is it possible to then display which file the parsed content comes from in my loop?
try this:
var arr = ["file1.xml", "file2.xml"],
cnt = 0, xhr = new XMLHttpRequest(), method = "GET";
function formatXml(file, xmlDoc) {
var x=xmlDoc.getElementsByTagName("TAGNAME");
console.log(file,x);
}
function getXml() {
xhr.open(method, arr[cnt], true);
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
formatXml(arr[cnt], xhr.responseText);
cnt++;
if (cnt < arr.length) getXml(); // call again
}
};
xhr.send();
}
getXml(); // start it

Junk after document element. How to avoid XML parsing with ajax get (XMLHttpRequest) in vanilla javascript?

Firefox & AJAX Junk after document element
I'm having pretty much the exact same problem as the above question, but for different reasons.
To reiterate the problem:
I have some html file:
<style> #hat { color: red; } </style>
<script> var hat = "fez"; </script>
Which I'm retreiving via vanilla ajax call:
var request = new XMLHttpRequest();
request.open('GET', target, true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success!
var response = request.responseText;
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
That is throwing an error in console:
junk after document element
I don't want the html file parsed at all. I've tried searching for a non XML HttpRequest method, but JQuery is all I can find on the subject. Perhaps there is something like a TextHttpRequest that just retrieves text without parsing it? Or maybe there's a way to tell an XMLHttpRequest that parsing is unnecessary?
This all seems like it should be pretty obvious, but I just keep finding tutorials on ajax that use jquery.
Here's a link to the MDN
All you should need to do is add this line before .send():
request.responseType = 'text';
This worked for me:
var request = new XMLHttpRequest();
// add a responseType here
request.responseType = 'text';
request.open('GET', target, true);
request.onload = function() {
if (request.status == 200) {
// Success!
var response = request.responseText;
document.body.innerText = response;
} else {
// We reached our target server, but it returned an error
alert('there was an error in the response.\n\n Error: ' + request.status);
}
};
request.onerror = function() {
// There was a connection error of some sort
alert('there was an error in the request');
};
request.send();

Raw javascript eq of ajax post is not working correctly [duplicate]

This question already has answers here:
Send POST data using XMLHttpRequest
(13 answers)
Closed 7 years ago.
I am trying to make some ajax post raw js script and I am using one of the questions asked here in stackoverflow but I encountered a problem.
var r = new XMLHttpRequest();
r.open("POST", "###URL###", true);
r.onreadystatechange = function () {
if (r.readyState != 4 || r.status != 200) return;
console.log(r.responseText);
};
console.log(price);
r.send("prize=" + prize);
return false;
When I check in chrome network the payload is sent correctly prize=632 but the result of the php script with $_POST['prize'] is empty. Where can the problem be?
Best regards!
You are missing the headers:
var data = "prize=" + prize;
var r = new XMLHttpRequest();
r.open("POST", "###URL###", true);
// Send the expected headers information along with the request
r.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
r.setRequestHeader("Content-length", data.length);
r.setRequestHeader("Connection", "close");
r.onreadystatechange = function () {
if (r.readyState != 4 || r.status != 200) return;
console.log(r.responseText);
};
console.log(price);
r.send(data);
return false;

check if network connection exists in javascript [duplicate]

This question already has answers here:
Check if Internet Connection Exists with jQuery? [duplicate]
(9 answers)
Closed 9 years ago.
I want to check if network connection exists at runtime in javascript. I am using window.navigator.onLine but its not working.
<script language="javascript">
alert(window.navigator.onLine);
</script>
it is returning true always
You could try using an AJAX call with a short timeout and handling the success/error.
You can do it as below :
if (navigator.onLine) {
alert("online");
}
or as below :
var xhr = new XMLHttpRequest();
xhr.addEventListener('readystatechange', state_change, true);
xhr.open("GET", url, true);
xhr.send(null);
function state_change(){
if(xhr.readyState == 4){
if(xhr.status == 200){
console.log('worked');
} else if(xhr.status == 0) {
console.log('no internet');
} else {
// Some other error
}
}
}

Categories

Resources