What does XMLHttpRequest do in that code - javascript

I'm a beginner in Javascript , and I want to understand what the method XMLHttpRequest does.
This is the code that I was reading, and I was wondering if someone could explain what it is doing:
var xhttp;
xhttp=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP"),xhttp.open("GET","script.php",!0),xhttp.send();

Hi I am not really good in explanations, but I will try to explain this in details as I see and understand this.
The XMLHttpRequest is an object. It is used for exchanging of data with a server. So with its use you can send some data to the script on the server(request) and get some data back from it(response). That response data can be displayed instantly on the page without page reloading. So this process call AJAX.
I would read your provided code as
//define a variable
var xhttp;
/*assign a XMLHttpRequest object to this variable
check if the global object window has a XMLHttpRequest object already
if not and user have a newer browser, create one (new XMLHttpRequest - for IE7+, Firefox, Chrome, Opera, Safari browsers) or user have an older browser (ActiveXObject("Microsoft.XMLHTTP") - for IE6, IE5 browsers)
xhttp.open method specifies the type of request(method GET, Script on server, asynchronous)
xhttp.send method sends the request to a server*/
xhttp=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP"),xhttp.open("GET","script.php",!0),xhttp.send();
But you have to check the readyState property of the XMLHttpRequest object as well
xmlhttp.onreadystatechange = function() {
//4: request finished and response is ready
//200: "OK"
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//display of returned data from the server
//it is available in this property - xmlhttp.responseText
}
}
The whole peace of code should look like:
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//display of returned data from the server
//jquery example
$('div').html(xmlhttp.responseText);
}
}
xmlhttp.open("GET", "script.php", true);
xmlhttp.send();
Hopefully this helped, good luck!

It's a reference to an AJAX request.
See more at the MDN site.
In a nutshell, it is sending a GET request to script.php.

An XMLHttpRequest is a JavaScript object made for making AJAX request. I am not fully sure that code is correct. Usually you make an instance of the XMLHttpRequest object. Then you check the window ready state to make the request. Finally you make the request. This is an example of that:
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
callback(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
I hope that helps!
Happy coding!

Related

Submitting code snippets to database using XMLHttpRequest

In my website, I send data to a database using XMLHttpRequest. I tried submitting code snippets and simple Spanish language characters, but when I check the received data, I only see what comes after those code snippets or characters, like this:
Data sent:
Hello <?xml version="1.0" encoding="utf-8"?>
Data received:
Hello
So, is there any way to submit code snippets or special characters using XMLHttpRequest? If there isn't, which is the best way besides php?
Here is my XMLHttpRequest code:
//call the function for the XMLHttpRequest instance
//create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
var xmlHttp;
if(window.XMLHttpRequest) {//for Forefox, IE7+, Opera, Safari, ...
xmlHttp = new XMLHttpRequest();
}else if(window.ActiveXObject) {//for Internet Explorer 5 or 6
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//create pairs index=value with data that must be sent to server
var data = "title="+title+"&desc="+desc;
//sets the request
xmlHttp.open("POST","http://mywebsite.com/database.php",true);
//adds a header to tell the PHP script to recognize the data as is sent via POST
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//sends the request
xmlHttp.send(data);
//Check request status
//If the response is received completely, will be transferred to the HTML tag with tagID
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
document.getElementById("div").innerHTML=xmlHttp_refresh_es_ES.responseText;
}
}
Always encode your data before sending it, that way spaces and special characters shouldn't be an issue (as long as it's UFT8)
var data = "title=" + encodeURIComponent(title) + "&desc=" + encodeURIComponent(desc);

Arduino wifi shield server - can't access "get" http response using JQuery

I have an arduino wifi shield which is running the standard code that is provided in the tutorial (http://arduino.cc/en/Tutorial/WiFiWebServer). Then I go on chrome and access the ip address that arduino server is running on. Here is prints out the data that is required, so I see the page being updated and everything.
Now I want to access that data from my computer through an html page. I used the following to "GET" the data from that address however this is giving me problems. I am unable to get this to work. I can't get the status to ever be 200. I always get a 0.
<div id="myDiv"></div>
<script>
alert(window.location.host);
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
//alert(xmlhttp.readyState);
alert(xmlhttp.status);
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "http://192.168.0.101/", true);
xmlhttp.send();
</script>
My computer and the shield are both on the same network as I am connecting to them through the same router. I can't seem to have any luck trying to configure this correctly.

XMLHttpRequest only works in IE

I am using the XMLHttpRequest object for my AJAX calls which has been working fine across browsers with a callback handler I have created to return JSON based on the request type and arguments etc.
But I am now integrating an external RESTful API to return a JSON string and for some reason it only works for me in IE (tested in IE 8). Using fiddler 2 I have determined that the API is returning the correct data.
I get the XMLHttpRequest.readyState of 4 but XMLHttpRequest.status only returns 0 for Chrome, Safari and FF. I read that sometimes when using a local server (test server) you always get a status of zero so I bypassed my check for status but still got a blank string for XMLHttpRequest.responseText.
function ajaxRequest(requestType,url) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
switch (requestType)
{
case 5:
//Home postcode search
showAddresses("home", xmlhttp.responseText);
break;
}
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
You should upgrade to jQuery as it will handle this request for nearly all browsers. But if you really want to know how to use XMLHttpRequest across all browsers, here's some code that seems to do the trick: https://github.com/ilinsky/xmlhttprequest/blob/master/XMLHttpRequest.js
Or, just pick apart jQuery's implementation.
http://api.jquery.com/category/ajax/
Hope this helps.
My issue was that I was using an external API and xmlHttpRequest only allows you to makes calls on the same server. I moved my data call into my server code and got the response from my callback handling page instead of going straight out to the API.

Why is my basic Ajax script not working?

I have been playing around with Javascript and now I came to Ajax. I am trying to write very simple script that would get the file contents - print the txt file contents in the div with id=test. This is the script :
function loadXMLDoc(url)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET" , url ,false);
xmlhttp.send(null);
document.getElementById('test').innerHTML = xmlhttp.responseText;
}
when I use it on this website :
<div id="test" name="test"> HELLo </div>
<button type="button" onclick="loadXMLDoc('test1.txt')">ClickMe1</button>
With this script HELLo is substituted by nothing - the script empties the container.
Maybe I am missing something trivial but do I need PHP installed ? I don't think so but... I am not sure what is happening in here. When I am debugging the xmlhttp is empty the whole time. Why ?
You'll need to check for readyState and the HTTP response status before replacing the text;
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("test").innerHTML=xmlhttp.responseText;
}
example on http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp
Please let me know if it works.
For browsers other than IE
IE's active X object seems not to care much about the ready state, other browsers may not have the text loaded quickly enough at the time you run your function (hence why you are getting the blank instead of file contents). IE's active X seems to handle this automatically and ignores the ready state, so you have to break up the code differently as below. Normally you check the status of the request to see if it's been fully read or not before accessing the responseText.
Add onreadystatechange you cannot check the status attribute since there is no HTTP requests being made on a file system request. (The status will always be 0 for request not made via HTTP) The best I can offer is this:
function loadXMLDoc(url)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
document.getElementById('test').innerHTML = xmlhttp.responseText;
}
xmlhttp.open( "GET", url );
xmlhttp.send(null);
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open( "GET", url );
xmlhttp.send(null);
document.getElementById('test').innerHTML = xmlhttp.responseText;
}
}
For CHROME
If you are using CHROME you must start chrome up with the --allow-file-access-from-files switch. Otherwise, it will refuse file system ajax requests. (You will have to set this even if using a so-called "easier" library such as jQuery).
Running AJAX apps on File System In General
Not usually a good idea, a lot of caveats to this route. Typically local development is done with a web server installed to localhost on your development machine.
Today its old fashion to call ajax like xmlhttp = new XMLHttpRequest();
You have many other options for this.
http://api.jquery.com/jQuery.ajax/
http://www.w3schools.com/jquery/jquery_ref_ajax.asp
http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/
Firstly, you have to fight with Same Origin Policy.
A simple working code for a synchronous request is following:
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.status == 200 && req.readyState == 4) {
...
}
req.open('GET', url, true);
req.send(null);
Note this is working for Firefox/Opera/Chrome. If IE, use:
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
You need a server to listen up to requests. Your regular file system will not be able to respond to AJAX requests.
You don't need PHP, however you'll need apache or a similar web server.
Try with jQuery. Download the last version here and write this code snippet:
function loadXMLDoc(url) {
$("#test").load(url);
}
It's much simpler and less error prone

Load specific XML content to HTML

I'm trying to load specific content from a XML to a HTML div. I'm using a function with parameters to do this.
This my call to function:
loadDoc("news.xml","destak-article","article");
this should send a request for the xml file, get the content of «article» tag and put it on the «destak-article» div.
Here's my function body:
function loadDoc(url,id,tagname){
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
xmlhttp.open("GET",url,false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
document.getElementById(id).innerHTML = xmlDoc.getElementsByTagName(tagname)[0].childNodes[0].nodeValue;
}
But this doesn't seem to work.
On Chrome js console I get this error: Cannot call method 'getElementsByTagName' of null
On Firebug I get: xmlDoc.getElementsByTagName(tagname)[0] is undefined
Any help is much appreciated.
Did you verify the server response? Use some error checking in your code. For example:
if (xmlhttp.status == 200) {
document.getElementById(id).innerHTML = xmlDoc.getElementsByTagName(tagname)[0].childNodes[0].nodeValue;
}
else {
alert('error');
}
You need to register a handler function that will be called once the request is complete. You can see an example of how to do that here.
What's happening in your case is that you're trying to get the xmlDoc immediately after sending the request and the server hasn't had time to process the request and respond yet.

Categories