XMLHttpRequest the hard way
By Anatoly Mironov
$.ajax is great, it hides much of the complexity. But sometimes we need to work with “raw” javascript :) So let’s look behind the scenes. The XMLHttpRequest (or just XHR) is used to open a connection to a server without a page reload. Internet Explorer calls it ActiveXObject and it differs in IE versions. Wikipedia article gives a good example how to create one constructor for all browsers: [sourcecode language=“javascript”]if (typeof XMLHttpRequest == “undefined”) XMLHttpRequest = function () { try { return new ActiveXObject(“Msxml2.XMLHTTP.6.0”); } catch (e) {} try { return new ActiveXObject(“Msxml2.XMLHTTP.3.0”); } catch (e) {} try { return new ActiveXObject(“Microsoft.XMLHTTP”); } catch (e) {} //Microsoft.XMLHTTP points to Msxml2.XMLHTTP and is redundant throw new Error(“This browser does not support XMLHttpRequest.”); };[/sourcecode] The remainder is more or less the same among the browsers. We open a connection defining the HTTP verb, URI and async mode (true or false): [sourcecode language=“javascript”]var xhr = new XMLHttpRequest(); xhr.open(“GET”, “/_vti_bin/listdata.svc”, true); xhr.onreadystatechange = onStateChange; xhr.send(null);[/sourcecode] Pay attention to onreadystatechange (only lower case letters). If we choose async=false, the UI waits for the response which is not so kind to users, but maybe it is easier to write a program. Well, there is actually no option but to have async=true. To provide the callback for success and error we can write the responding function onreadystatechange. This function will be called every time the state is changed. There are 5 states:
0 = uninitialized
1 = loading
2 = loaded
3 = interactive
4 = complete
```The state 4 "complete" and status 200 (OK) means success. \[sourcecode language="javascript"\]function onStateChange() { if (xhr.readyState == 4) { if (xhr.status == 200) { response = xhr.responseText; } } }\[/sourcecode\] This **onreadystatechange** is actually cool stuff. It helps to understand how ajax actually works, and how jQuery "is talking" to browser in order to partially load data. The **onreadystatechange** callback function opens even new opportunities. [What if you want to show a spinner when the data has began to load](/2012/02/12/loading-notification/ "See my blog post about spin.js. Show spinner without images")? Very simple. Let's just add a couple of code lines to our onStateChange function. When the state is 1 (loading) - show, when 4 (complete) - hide. Suppose we have a spinner object already: \[sourcecode language="javascript"\]function onStateChange() { if (xhr.readyState == 1) { spinner.spin(); } if (xhr.readyState == 4) { spinner.stop(); if (xhr.status == 200) { response = xhr.responseText; } } }\[/sourcecode\] By the way, [if you must parse XML from response, check out this blog post by Santosh](http://aspdotnetcodebook.blogspot.com/2008/05/how-to-read-xml-using-javascript.html "How To Read XML Using Javascript")
#### Sys.Web.Request (Update 2013-03-05)
In ASP.NET there is a wrapper for this: Sys.Web.Request. I found it in [a question on SharePoint stackexchange](http://sharepoint.stackexchange.com/questions/58674/ecma-js-csom-retrieving-items-from-multiple-lists-with-async-processing-how). Here is a simple example without any error handling, without any parameters, just to show how to invoke the Sys.Web.Request: \[sourcecode language="javascript"\] function onCompleted(response, eventArgs) { var results = response.get\_responseData().d.results; } var url = "the actual url"; var request = new Sys.Net.WebRequest(); request.set\_httpVerb("GET"); request.set\_url(url); request.get\_headers()\["Accept"\] = "application/json"; request.add\_completed(onCompleted); request.invoke(); \[/sourcecode\]
#### SP.RequestExecutor
Another way to make an ajax call is to use SP.RequestExecutor which is javascript utility available in SharePoint 15 (maybe not only 15?) under /\_layouts/15/sp.requestexecutor.js. I found this thanks to a question on SharePoint StackExchange: [Upload a non-text as an attachment using SharePoint 2013 REST API](http://sharepoint.stackexchange.com/questions/60417/cant-upload-a-non-text-file-to-sharepoint-app-via-rest-api). I mentioned it in my other post: [REST API: Add a plain text file as an attachment to a list item](/2013/02/20/rest-api-add-a-plain-text-file-as-an-attachment-to-a-list-item/): \[sourcecode language="javascript"\] var request = new SP.RequestExecutor("/"); request.executeAsync({ url: "MY URL", method: "GET" }); \[/sourcecode\]