Friday 25 February 2011

JQuery how to pass data to a servlet on the server via AJAX

This is a short note about passing data to a servlet on the server.
using AJAX on JQuery. The problem is you can not find the required
format written anywhere.

-The passed data must be in the name-value format as seen below.
-The content type is indicated wrong in many internet references,
probably version difference.
-The JQuery version I used is jQuery JavaScript Library v1.4.4
-be careful dataType "json" does not work it has to be capitolized.

The complete application uses multiple buttons that trigger multiple
AJAX calls. I will provide the full working code as I make progress.
Calling and returning back from AJAX driven servlets is working now.

Cheers.

Ali R+

Here is the solution:
...
...
...
var name = $("input#name").val();
var last = $("input#last").val();
var hobby = $("input#hobby").val();

var aoData = [];

aoData.push( { "name": "name", "value": name },
{"name": "last", "value": last },
{"name": "hobby", "value": hobby }
);
$.ajax({
type:"POST",
url: "./new",
contentType: "application/x-www-form-urlencoded",
dataType: "JSON",
data: aoData,
success: function(data) {
var jsonData = $.parseJSON(data);
$("input#name").val(jsonData.name)
$("input#last").val(jsonData.last)
$("input#hobby").val(jsonData.hobby)
}
})
return false;
...
...
...