CHUVASH.eu

CHunky Universe of Vigourous Astonishing SHarepoint :)

XMLHttpRequest the hard way

$.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:

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.");
};

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):

var xhr = new XMLHttpRequest();
xhr.open("GET", "/_vti_bin/listdata.svc", true);
xhr.onreadystatechange = onStateChange;
xhr.send(null);

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.

function onStateChange() {
  if (xhr.readyState == 4) {
    if (xhr.status == 200) {
      response = xhr.responseText;
    }
  }
}

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? 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:

function onStateChange() {
  if (xhr.readyState == 1) {
    spinner.spin();
  }
  if (xhr.readyState == 4) {
    spinner.stop();
    if (xhr.status == 200) {
      response = xhr.responseText;
    }
  }
}

By the way, if you must parse XML from response, check out this blog post by Santosh

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. Here is a simple example without any error handling, without any parameters, just to show how to invoke the Sys.Web.Request:

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

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. I mentioned it in my other post: REST API: Add a plain text file as an attachment to a list item:

var request = new SP.RequestExecutor("/");
request.executeAsync({
	url: "MY URL",
	method: "GET"
});
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Вула Чăвашла

VulaCV - Чăвашла вулаттаракан сайт

Discovering SharePoint

And going crazy doing it

Bram de Jager talking Office 365, SharePoint and Azure

My view and thoughts on Productivity and more.

My programming life

and everything in between

SharePoint Development Lab by @avishnyakov

It is a good place to share some SharePoint stories and development practices.

SharePoint Dragons

Nikander & Margriet on SharePoint

Paul J. Swider - RealActivity

RealActivity is a specialized healthcare services and solution advisory firm.

Mai Omar Desouki - Avid SharePointer

Egyptian & Vodafoner - Senior SharePoint Consultant

Cameron Dwyer | Office 365, SharePoint, Outlook, OnePlace Solutions

Office 365, SharePoint, OnePlace Solutions & Life's Other Little Wonders

paul.tavares

Me and My doings!

Share SharePoint Points!!

By Mohit Vashishtha

Jimmy Janlén "Den Scrummande Konsulten"

Erfarenheter, synpunkter och raljerande om Scrum från Jimmy Janlén

SPJoel

SharePoint for everyone

SharePointRyan

Ryan Dennis is a SharePoint Solution Architect with a passion for SharePoint and PowerShell

SharePoint 2020

The Vision for a Future of Clarity

Aharoni in Unicode

Treacle tarts for great justice

... And All That JS

JavaScript, Web Apps and SharePoint

%d bloggers like this: