lauantai 10. elokuuta 2013

Javascript: How to send just one form element by Ajax with XMLHttpRequest 2

Because of HTML5, we have new XMLHttpRequest level 2 API and FormData-object which let us to create a custom POST data.  In this post I am not going to explain all details about new Ajax possibilities, that is done in article "New Tricks in XMLHttpRequest2".

In article written by Eric Bidelman, is explained in nice way how to create a FormData-object from particular form-element. So we can turn any form into a FormData-object by giving a form-element from DOM to FormData constructor.

var myform=document.getElementByTagName('form')[0]
var formdata=new FormData(myform);

This will create an formdata variable which can be send to server by Ajax.

What Eric does not tell in article, is that FormData object can be feeded only with Form element, and in object itself it is not possible to choose which form controls will be included and which should be left behind. This is how it different from jQuery's $.serialize or $.serializeArray, which does not care if form controls actually are inside a form element or not.

In real life, it is sometimes needed to send to the server only particular section of form or an individual form control. Lets assume we have an lonely textinput which we would like to send to an server.
<input type="text" name="address" id="myinput">

As now, it is not possible to create a FormData object, because the input is not inside a form.
However, following functions will make it happen:

function createFormData(elem) {
var dataform=document.createElement('form');
return new FormData(dataform);

With the function it is possible to create an FormData object from single input:

var inputelement=document.getElementById('myinput')
var formdata=createFormData(inputelement)

Finally we can send the input to a server:

var xhr = new XMLHttpRequest();'POST', 'mywebpage', true);
xhr.onload = function(e) { ... };

Ei kommentteja:

Lähetä kommentti