Friday 28 November 2014

Things I wish that Javascript did better in the browser: AJAX

I've been trying to write the shortest possible generic function that I can call to make an AJAX request. My best attempt is around 100 lines of code. Here's the basic code:

var el = document.getElementById("message"); 

var xmlHTTP = new XMLHttpRequest(); 

xmlHTTP.open(method, "service/messages", true); 

xmlHTTP.onreadystatechange = function() { 
 if (xmlHTTP.readyState == 4 || xmlHTTP.readyState == "complete"){ 
  el.innerHTML=xmlHTTP.responseText ;
 } 
};

xmlHTTP.send(body);

The first problem is that the event listener onreadystatechange is far to broad so it ends up always having to hold conditional logic. How about an onready listener instead?

Secondly, the stateful XMLHttpRequest object could pass a reference to itself or a separate response object to the listener.

Thirdly, I don't see why the XMLHttpRequest can't have a another constructor that allows you to pass in the url and the onreadystatechange (or onready) function:

new XMLHttpRequest("my-service-endpoint",onready); 

Also as well as the open() method, we could have get() post() and del() methods:

new XMLHttpRequest("my-service-endpoint",onready).get(); 
new XMLHttpRequest("my-service-endpoint",onready).del(); 
new XMLHttpRequest("my-service-endpoint",onready).post(body);

These are minimal changes to the existing api which would allow us to make AJAX calls in one statement:

var el = document.getElementById("message"); 
new XMLHttpRequest(
 "service/messages",
  function(response){ 
      el.innerHTML=response.text; 
  }
).get();

Update: Looks like they have started to deal with the first issue by adding an onload event. It would nicer still to be able to pass this as a constructor argument in XMLHttpRequest. http://www.html5rocks.com/en/tutorials/file/xhr2/

1 comment:

  1. My latest thought on the javascript wishlist: document.getNodesByXPath('text()');

    http://stackoverflow.com/questions/2579666/getelementsbytagname-equivalent-for-textnodes

    (Discovered this could be useful when playing with a toy-script: http://stackoverflow.com/questions/28488047/is-there-a-way-to-only-replace-the-innertext-of-all-elements-on-a-page)

    ReplyDelete