Parsing JSON url in pure javascript - javascript

I'm trying to parse a url in pure javascript, just one executable file.
url = 'http://myurl.php?format=json'
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
var mystuff = JSON.parse(request.responseText);
} else {
// some error
}
};
request.onerror = function() {
// some error
};
request.send();
console.log(mystuff);
When I do this, I get a XMLHttpRequest is not defined error. What's the best way to do this, the simplest way?
Thank you.

This statement is wrong you should url as a variable not "url" as a string,
request.open('GET', 'url', true);
to
request.open('GET', url, true);
Furthermore the xmlHttpRequest works only on some versions of browsers.
You could do something like this to check whether xmlhttpRequest works on your browser,
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}

Related

Javascript make HTTP request on regular interval not working

I have a page to show the chat messages. I need to refresh the chat body every 30 seconds to load the new messages. I have set the interval to 30 seconds , the function is running , but its not making the HTTP request. Here is my code
function loadmessages(){
var ids = document.getElementById("pid").value;
var request = new XMLHttpRequest();
request.open("get", '/refresh_message/'+ ids );
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.setRequestHeader("X-CSRF-TOKEN", document.querySelector('meta[name="csrf-token"]').content);
request.onload = function(){
if(this.status == 200){
var resp = JSON.parse(this.responseText);
console.log(resp.message);
}
else{
console.log(this.status);
}
request.send(null);
}
}
loadmessages();
setInterval(function(){
loadmessages()
}, 30000);
Consistent indentation matters. You're putting request.send(null); inside the request.onload function, so of course it never gets sent in the first place. Try putting it outside, instead:
function loadmessages() {
var ids = document.getElementById("pid").value;
var request = new XMLHttpRequest();
request.open("get", '/refresh_message/' + ids);
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.setRequestHeader("X-CSRF-TOKEN", document.querySelector('meta[name="csrf-token"]').content);
request.onload = function() {
if (this.status == 200) {
var resp = JSON.parse(this.responseText);
console.log(resp.message);
} else {
console.log(this.status);
}
}
request.send(null);
}

Navigate to URL with custom request headers in JavaScript

Question just like the title.
In command line, we can type:
curl -H "header_name: header_value" "http://example"
to navigate to http://example with a custom request header as shown above.
Q: If I need to write a JavaScript to do the same thing, how should I do?
var url = 'https://example';
var myRequest = new XMLHttpRequest();
myRequest.open('GET', url ,false);
myRequest.setRequestHeader('header-name','header-value');
myRequest.send();
I tried this code, there is no syntax error but the page didn't change. Hence, I don't really know if I modified the request header(s).
Here is how you can handle this:
var req = new XMLHttpRequest();
req.open('GET', 'http://example', true); //true means request will be async
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4) {
if(req.status == 200)
//update your page here
//req.responseText - is your result html or whatever you send as a response
else
alert("Error loading page\n");
}
};
req.setRequestHeader('header_name', 'header_value');
req.send();

Ionic controller XMLHttpRequest function doesn't work

does somebody know why this doesn't work? I get a error message at 'request.status' in Ionic
.factory('Nieuws', function() {
var url = "http://echo.jsontest.com/ID/2/bericht/test";
var request = new XMLHttpRequest();
request.open("GET", url);
var nieuws;
request.onload = function () {
if (request.status = 200) {
nieuws = JSON.parse(request.responseText);
//console.log(nieuws);
}
};
You're trying to assign a value to a read only property when you need to be making a comparison.
Replace = with ==.

is there a race condition in this javascript?

In the following js snippet
request = new XMLHttpRequest
request.open('GET', '/my/url', true)
request.send()
request.onload = function() {
data = JSON.parse(this.response)
}
should the assignment of the on load be before the send() to avoid a race condition. Or does the browser deal with it for you (by firing the on load when you get round to assigning it).
Your request should look more like:
var request = new XMLHttpRequest || new ActiveXObject('Microsoft.XMLHTTP');
request.open('GET', '/my/url');
request.onreadystatechange = function(){
if(request.readyState == 4 && request.status == 200){
console.log(request.responseText);
}
}
request.send();
To further answer your question request.send() should happen last, because if the response comes back before the function is assigned to request.onreadystatechange, there could be a problem, although it's very unlikely that the response would be that fast.

XMLHttpRequest alters text in UTF-8

While processing a huge XML client-side, got stuck with the following issue: some unicode characters are replaced with unreadable sequences, so server cannot parse that XML. Testing like this:
var text = new XMLSerializer().serializeToString(xmlNode);
console.log(text);
var req = new XMLHttpRequest();
req.open('POST', config.saveUrl, true);
req.overrideMimeType("application/xml; charset=UTF-8");
req.send(text);
Logging still shows the correct string:
<Language Self="Language/$ID/Czech" Name="$ID/Czech" SingleQuotes="‚‘" DoubleQuotes="„“" PrimaryLanguageName="$ID/Czech" SublanguageName="$ID/" Id="266" HyphenationVendor="Hunspell" SpellingVendor="Hunspell" />
While in the request (Chrome dev tools) and at server side it appears modified like this:
<Language Self="Language/$ID/Czech" Name="$ID/Czech" SingleQuotes="‚‘" DoubleQuotes="„“" PrimaryLanguageName="$ID/Czech" SublanguageName="$ID/" Id="266" HyphenationVendor="Hunspell" SpellingVendor="Hunspell" />
Original encoding of the XML file is UTF-8, too. Absolutely the same behavior when using jQuery.
Check that overrideMimeType use uppercase "UTF-8" or lowercase "utf-8"
Make sure that string before javascript calculation was in utf-8 (check page charset)
Use escape/encodeURIComponent/decodeURIComponent before send it to server and unescape it on server
Try application/x-www-form-urlencoded ans send xml like plain text
P.S. Modified string is in ISO-8859-15
It seems to do so.
I have here data json parameter that includes a string "Lääke" (finnish word), that i sent to server via ajax.
This did NOT work, server app did not receive 'ää' but '??':
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
status = this.responseText;
if (status === "OK") {
window.location.assign("ackok.html");
}
else {
window.location.assign("ackerror.html");
}
}
};
xhttp.open("POST", "ProcessOrderServlet?Action=new&Customer="+data, true);
xhttp.send();
This did work, server received 'ää':
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
status = this.responseText;
if (status === "OK") {
window.location.assign("ackok.html");
}
else {
//orderStatusElement[0].innerHTML = "<b>Palvelimella jokin meni vikaan. Yritä myöhemmin uudelleen </b>";
window.location.assign("ackerror.html");
}
}
};
xhttp.open("POST", "ProcessOrderServlet?Action=new&Customer="+data, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send();

Categories