Thursday, May 12, 2011

JQuery UI autocomplete with POST

jQuery UI is awesome, but some of the features are not as flexible as the framework itself, for example, I would prefer all http requests to use POST instead of GET, and I would prefer all data to be transferred using JSON instead of other data format.

jQuery's autocomplete is one of the widget that will work only with simple string or array, and by default it uses GET.

Below is my solution to autocomplete with POST, and accepting JSON response from the server:

I have added field as the search field, and filter as the filter to limit search range to the function and it is working well.


The JSON format returned is [{"name":"Kuala Lumpur"},{"name":"Kuala Tembeling"}] using PHP's json_encode function.

function autoComplete(node, model,field,filter){

var url="/test/"+model+"/autocomplete";

node.autocomplete({

source: function(request, response){

var inData=[];

inData.push({'name':'data[term]','value':request.term});

inData.push({'name':'data[field]','value':field});

inData.push({'name':'data[filter]','value':filter});

$.ajax({

"dataType": 'json',

"data": inData,

'async':true,

"type":"POST",

"url": url,

"success": function( data ) {

response( $.map( data, function( item ) {

return {

label: item.name,

value: item.name

}

}));

}

});

}

});

}


No comments:

Post a Comment