JavaScript code not working across browsers - javascript

var txt = http.responseText; -> it doesnt work in Chrome...
how i can change this line?

You should call method send at the end:
var http = new XMLHttpRequest();
var url = "http://example.com/logScore.php";
var params = "GameID=5&User="+name+"&Score="+score+"";
http.open("GET", url+"?"+params, true);
http.onreadystatechange = function() {//whatever you want}
http.send();
Without calling send request will not be send.

Doing AJAX and having it work X-Browser with vanilla-JS is a pain in the ass. I definitely recommend a library (like jQuery) to do this for you. Please see this answer for how to do it with plain JS:
Easiest way to retrieve cross-browser XmlHttpRequest

Related

XHR Post for saving document.body JS

i need to post document.body.innerHTML to my domain's proxy. There is working PM2 and before it I used GET and it looked like:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://domain.ru/pmproxy?info='+document.body.innerHTML+'&location='+document.location+1);
xhr.send();
Now, because there is a limit of letters I need to us POST. How can I turn this into POST?
First make sure the receiving server method accepts post and if you want to send data in xhr post you can do like this
xhr.send("info='+document.body.innerHTML+'&location='+document.location+1")
or if a server accepts a json object then you can use xhr.send(document.getElementById('#form).serialize());
You should convert it to this:
var xhr = new XMLHttpRequest();
xhr.open('post', 'https://domain.ru/pmproxy');
xhr.send('info='+document.body.innerHTML+'&location='+document.location+1);
Also, I suggest you clean both parameters, so you can avoid problems in the future:
xhr.send('info='+encodeURIComponent(document.body.innerHTML)+'&location='+encodeURIComponent(document.location+1));
Furthermore, I don't really know why you're using document.location+1, but you can use document.location.href and save the +1 so your code looks cleaner:
xhr.send('info='+encodeURIComponent(document.body.innerHTML)+'&location='+encodeURIComponent(document.location.href));

Getting started with calling APIs via XMLHttpRequest

I've just started to learn how to use APIs, but I'm having a little bit of trouble understanding exactly how to utilize them.
I was able to write the following code thanks to some online documentation, but I have some questions about how to add to it:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=London&mode=xml", false); xhr.send();
console.log(xhr);
Now, when I run this code in my browser and I open the console, I get a dropdown with a whole bunch of stuff under it. First of all, how can I get the code to display JUST the response? I want the console to display just the XML to show when I run my code. Second of all, how do I parse the XML? Is there any way to get a value from an XML element and assign it to a JavaScript variable?
Thanks!
What you are printing is the XMLHttpRequest object itself, while what you actually want is the response from the request you've made. To get the response, you use
xhr.responseXML;
Which is a object of the type document. (See the MDN docs).
To exhibit the code, you can just
console.log(xhr.responseXML);
But to actually work with the response, you'll probably want to do as Josh suggested, and request from the API a JSON-formatted response (instead of a XML-formatted one).
You will probably want to do that asyncronously, too (see this). The page has a more robust example. Let's adapt it to show London's temperature:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=London&mode=json", true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseText);
var response = JSON.parse(xhr.responseText);
console.log("Temperature(K): " + response.main.temp);
} else {
console.error(xhr.statusText);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
xhr.send(null);
Being async means that the xhr.onLoad function will be executed as soon as the response is received. Thus all of your code will be executed sequentially, and only when the response is received the onLoad will be executed.
You can get the response as a Document object.
Using your code above, you can reference xhr.responseXML and use the Document documentation to learn how to grab what data you need.
That dropdown is probably your browser formatting the response object in an interactive way for you.
xmlDoc=xhr.responseXML; will give you the actual resulting text
Alternatively: you could request a JSON object to make working with the data much easier.
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=London&mode=json", false); xhr.send();
var data= JSON.parse(xhr.responseText); //data is now a javascript object full of the API data
Note how the url now reads mode=json now.

Trouble loading external page

I have a problem loading an external page into my div using Javascript. I get a NS_ERROR_FAILURE in the console.
var req = new XMLHttpRequest();
req.open("GET", 'helpInfo.html', false);
req.send(null);
var page = req.responseText;
document.getElementById("helpInfo").innerHTML = page;
If you want to use javascript you can build a Node.js server and route all your calls through that. That will help the XSS problem.

XMLHttpRequest to read an external file

I want to retrieve the data contained in a text file (from a given URL) through JavaScript (running on the client's browser).
So far, I've tried the following approach:
var xmlhttp, text;
xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', 'http://www.example.com/file.txt', false);
xmlhttp.send();
text = xmlhttp.responseText;
But it only works for Firefox. Does anyone have any suggestions to make this work in every browser?
Thanks
IT works using xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); in IE older versions. Chrome, Firefox and all sensible browsers use xhr
Frankly, if you want cross browser compatibility, use jquery
its pretty simple there:
var text="";
$.get(url, function(data){text=data;//Do something more with the data here. data variable contains the response})
var xhr = new XMLHttpRequest();
xhr.open('POST', '/uploadFile');
var form = new FormData();
form.append('file', fileInput.files[0]);
xhr.send(form);
It was previously impossible to upload binary data with XMLHttpRequest object, because it could not stand the use of FormData (which, anyway, did not exist at that time) object. However, since the arrival of the new object and the second version of XMLHttpRequest, this "feat" is now easily achievable
It's very simple, we just spent our File object to a FormData object and upload it

Is there any way to send binary data with XMLHttpRequest object?

I'am trying to send binary chunk with XMLHttpRequest
var xhr = new XMLHttpRequest();
var bindata = 0x0f0f;
xhr.open("POST", "binary_reader.php");
xhr.send(bindata);
But this approach not works. I've tried to provide Content-type: application/octet-stream, Content-encoding headers for xhr and they don't work either. I am suspect that there is no way to compose request of such kind.
I would appreciate any help.
XMLHttpRequest.sendAsBinary is obsolete. Link
As MDN mentioned, you can directly send binary typed array:
var myArray = new ArrayBuffer(512);
var longInt8View = new Uint8Array(myArray);
// generate some data
for (var i=0; i< longInt8View.length; i++) {
longInt8View[i] = i % 256;
}
var xhr = new XMLHttpRequest;
xhr.open("POST", url, false);
xhr.send(myArray);
Yes you can send binary data using XHR. All you need to do is set the appropriate headers and mime-type, and call the sendAsBinary method instead of the simple send method. For example:
var req = new XMLHttpRequest();
req.open("POST", url, true);
// set headers and mime-type appropriately
req.setRequestHeader("Content-Length", 741);
req.sendAsBinary(aBody);
W3C has introduced Blob type to XMLHttpRequest in the latest specification. Currently I haven't seen any implementation so far but in near future this is definitely the way to download and upload binary data with XMLHttpRequest.
The section "Handling binary data" here describes how to send and receive binary data via XMLHttpRequest.

Categories

Resources