Friday, July 8, 2011

Web forms and null values

Say you are building a javascript intensive application using jQuery and you wanted to send a literal null value to a server. You may start with the default behavior using the jQuery.ajax function:

var data = {  some_value: null };
jQuery.ajax({
           url: url,
           type: "PUT",
           data: data
});


However you discover that the default content type is application/x-www-form-urlencoded, which means that jQuery will serialize the data it will send in the message body. I was surprised to see that jQuery sets literal values such as "null" to a parameter value, e.g. data[some_value]=null, because the W3C recommendation, you'll realize that the specification states that browsers should omit null values altogether. This leads to having most web applications frameworks like Rails receive a string value instead of an absence of value.

Oh no! Does that mean there is no way to set the value to null? One option is to use JSON as the requests mime/content/media type:


jQuery.ajax({
     url: url,
     contentType: "application/json",
     type: "PUT",
     data: JSON.stringify(data),
     processData: false 
});
The server web framework will now interpret the JSON correctly and you get what you need. NULLS!

No comments: