Blog for web designers

Jquery UI autocomplete with API request

Jquery UI autocomplete with API request is one of the recent thing I have done. I am going to share what I have done. In order to start with Jquery UI autocomplete with API request we will use jqueryUI plugin.

	autoComplete: function(input,apiUrl,selectCallback,renderCallback){
		$(input).autocomplete({
		    minLength: 3,
		    delay: 300, // this is in milliseconds
		    json: true,
		      source:function(request,response){
			        var $this = $(this);
			        var $element = $(this.element);
			        var previous_request = $element.data( "jqXHR" );
			        if( previous_request ) {
			            previous_request.abort();
			        }
			        $element.data( "jqXHR", $.ajax({
								  url:apiUrl,
								  method:"GET",
								  dataType: "json",
								  data: {callData:{text: request.term}},
								  success: function(responseData){
									response(responseData.data.results);
									$(input).removeClass("ui-autocomplete-loading");
								}
					}));
			 },
		      select:selectCallback,
			  create: function() {
			         $(this).data('ui-autocomplete')._renderItem = renderCallback
			     }
		 });
	},

The above function is a object based function also called as method. A method is the function which is associated with an object. You can simply see that I have used the existing autocomplete code from jQuery UI and add some customization. I have also add the feature to cancel the previous API request and give priority to call only the latest. So, if the user keep typing in the text box with 300 ms gap and after 3 words, it will start executing API for each word enter. So, the abort() function is going to handle such request. It will simply cancelled all the previous request.

	var app = {
	createApiPath : function(apiController, apiAction) {
		var jsonUrl = jsonAPIUrl + 'api/' + apiController + '/' +  apiAction + '/';
		return jsonUrl;
	},
	apiCustomPost: function (apiController, apiAction, callParams, callback) {
		$.ajax({
				url: this.createApiPath(apiController, apiAction),
				method: "post",
				data:{
						callData: JSON.parse(JSON.stringify(callParams)),
						api_version: 1,
						deviceType: 'web'
					},
				async: true,
				dataType: "json",
				success: callback,
				error: function (xhr, ajaxOptions, thrownError) {
			}
		});
	},
}

Santosh Shah

My name is Santosh Shah and blogs at santosh-shah.com


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.