JQuery Autocomplete source is a function - jquery-ui

I'm using JQuery UI autocomplete, for different fields. To get the data i'm using a function as the source. It work great!
I was wondering if there were a way of not using the anonym function in the source, but to declare a generic one which will have a parameter to redirect to the right URL.
I'm quite new in JS and JQuery and so I have no idea of what the parameters request and response are comming from in the anonym function.
Here is what I'm trying to do:
$ac.autocomplete({
//Call the function here, but what are the parameter request and response???
source: autocomplete(),
minLength: 1
});
Here is the function I'd like to call
function autoComplete(request, response, url) {
$.ajax({
url: '/Comp/'+url,
dataType: "json",
type: "POST",
success: function (data) {
response($.map(data, function(item) {
return { label: item, value: item, id: item };
}));
}
});
}
Thanks a lot for your help.

You should use
source: autoComplete
instead of
source: autocomplete()
One more remark. The default implementation of jQuery UI Autocomplete use only value and label and not use id.

Reformatting ur question will pose as solution to the problem .:)
$ac.autocomplete({
minLength: 1 ,
source: function(request, response, url){
var searchParam = request.term;
$.ajax({
url: '/Comp/'+url,
data : searchParam,
dataType: "json",
type: "POST",
success: function (data) {
response($.map(data, function(item) {
return {
label: item.Firstname,
value: item.FirstName
};
});
}
});//ajax ends
}
}); //autocomplete ends
The request and response objects are expected by jQuery UI . The request.term will give u the text that the user types and the response method will return the label and value items to the widget factory for displaying the suggestion dropdown
P.S : assuming ur JSON string contains a FirstName key !

I will give an example of a situation that happened to me, might serve as an example:
Situation: After the user selects a keyword with Jquery Autocomplete not allow it to be listed. Taking into account that the query is executed the same, ie the unamended cat. server-side.
The code looked like this:
$( "#keyword-search" ).autocomplete({
minLength: 3 ,
source: function( request , response ) {
var param = { keyword_type: type , keyword_search: request.term } ;
$.ajax({
url: URI + 'search-to-json',
data : param,
dataType: "json",
type: "GET",
success: function (data) {
response($.map(data, function( item ) {
/* At this point I call a function, I use to decide whether to add on the list to be selected by the user. */
if ( ! is_record_selected( item ) ) {
return item;
}
}));
}
});
} ,
select: function( event , ui ) {
/* Before you add, looking if there is any cell */
/* If it exists, compare the id of each cell not to add an existing */
if ( validate_new_keyword( ui ) ) {
add_cell( ui ) ;
}
} ,
});
/* Any validation... */
function validate_new_keyword( ui ) {
var keyword_id = $.trim(ui.item.id) ;
Any condition...
if (keyword_id > 0) {
return true ;
}
return false ;
}
/* This function checks if a keyword has not been selected by the user, it checks for the keyword_array. */
function is_record_selected( item ) {
var index = jQuery.inArray( item.id , keyword_array ) ;
return index == -1 ? false : true;
}
Obs: Thus it is possible to use a function inside "source" and "select". =p

Related

Ajax refresh in mvc div data

I am developing a MVC application, where I have a scenario to refresh a part of the page basically ajax...
<div id="ajax" style="width:10%;float:left">
#foreach (var item in #Model.SModel.Where(x=>x.StudentId==13))
{
<li>#Html.DisplayFor(score => item.StudentName)</li>
}
This is the div (part of the page) which I need to refresh on a button click. I have 2 js files, data.js and render.js...
data.js contains a template as follows:
makeAJAXCall =
function (url, params, callback) {
$.ajax({
type: "get",
timeout: 180000,
cache: false,
url: url,
dataType: "json",
data: params,
contentType: "application/json; charset=utf-8",
success: function (result) {
if (callback) {
callback(result);
}
},
error: function (req, status, error) {
}
return null;
}
});
};
getGrid = function () {
makeAJAXCall(urlCollection["getGridInfo"], "", function (result) {
renderer.renderGridInfo('ajax', result);
});
};
and render.js file is as follows:
renderGridInfo = function (area, data) {
$("#" + area).text(data);
};
return {
renderGridInfo: renderGridInfo
};
In the loading page on button click function as :
Service.addURL('getGridInfo', '#Html.Raw(#Url.Action("getGridInfo", "AjaxController"))');
Service.getGrid();
In the ajax controller, the code is :
public JsonResult getGridInfo()
{
return Json(model, JsonRequestBehavior.AllowGet);
}
But the problem I am facing is, the controller is returning the JsonResult , but the 'div' accepts the model and so the output is [object] [object] button click
Question: Is there any way to refresh this 'div' from the Jsondata returned by the controller?
I have to follow this type of design without using AjaxForm.
Look what happens:
1) you returns Json: return Json(model, JsonRequestBehavior.AllowGet);
2) you put returned Json object to the div's value: $("#" + area).text(data);
that's why you end up with json's representation inside div
You need to change it as follows:
1) assume you put html for that div to model's field called NewHtml
2) eptract html from the property of returned json: var returnedHtml = data.NewHtml;
3) use html() method instead of text(): $("#" + area).html(returnedHtml);

Autocomplete in Jqgrid returns Data from Server but dont know to put in View

This is my first post. stackoverflow is a wonderful place for developers. Here is my issue.
I am trying to use Autocomplete in JqGrid Edit Form. i successfully retrieved data from server using ajax call but dont know how to display it in the view. below is my code.
FrontEnd Code:
colModel :[
{name:'prf_articlename', index:'prf_articlename', width:90, editable:true, edittype:'text',
editoptions: {
dataInit:function(e){
$(e).autocomplete({
source: function(request, response,term) {
var param = request.term;
$.ajax({
url: '/Myelclass/AutoCompleteServlet.do?term='+param+"&action="+"artname",
success: function (data) {
response($.map(data, function(item) {
return {
label: item.label,
};
}));//END Success
},
});//END AJAX
},
minLength: 2,
});//END AUOTOCOMPLETE
}//END Dataint
}//END Dataint
},
BackEnd Code:
String term = request.getParameter("term");
List<AutoComplete> articlelist = prfbo.getArticleNameinEditGrid(term);
System.out.println("List Value " +articlelist.size());
JSONArray jsonOrdertanArray = JSONArray.fromObject(articlelist);
System.out.println(jsonOrdertanArray);
out.println(jsonOrdertanArray);
Any one help on this???
This is what I personally use in my project:
Inside colModel:
dataInit: function (elem) { NameSearch(elem) }},
The function:
function NameSearch(elem) {
$(elem).autocomplete({ source: '/Controller/NameSearch',
minLength: 2, autosearch: true,
select: function (event, ui) {
$(elem).val(ui.item.value);
$(elem).focus().trigger({ type: 'keypress', charCode: 13 });
}
})//$(elem).autocomplete
$(elem).keypress(function (e) {
if (!e) e = window.event;
if (e.keyCode == '13') {
setTimeout(function () { $(elem).autocomplete('close'); }, 500);
return false;
}
})//$(elem).keypress(function (e){
} //function NameSearch(elem) {
I'm also dealing with an Enter key press as well in the above function.
here is the complete code for my Autocomplete in jqgrid Edit form..
colModel :[
{name:'name', index:'name', width:90, align:'center', editable:true, hidden: false, edittype:'text',
editoptions:{
dataInit:function (elem) {
$(elem).autocomplete({
minLength: 2,
source: function(request, response,term) {
var param = request.term; //values we enter to filter autocomplete
$.ajax({
url: "myurl",
dataType: "json",
type:"GET",
success: function (data) {
response($.map(data, function(item) {
return {
//can add number of attributes here
id: item.id,
shform: item.shortform,
value: item.name,
clr : item.color, //here apart from name and id i am adding other values too
size: item.size,
remar:item.remarks,
subs: item.subs,
selec:item.selec ,
};
}));//END Response
},//END Success
});//END AJAX
},
select: function( event, ui ) {
// setting values to textbox in jqgrid edit form based on selected values
$('#textbox1').val(ui.item.id);
$('#textbox2').val(ui.item.shform);
$('#textbox3').val(ui.item.clr);
$('#textbox4').val(ui.item.size);
$('#textbox5').val(ui.item.sizeremar);
$('#textbox6').val(ui.item.subs);
$('#textbox7').val(ui.item.selec);
$('#textbox8').val(ui.item.selp);
}
});
$('.ui-autocomplete').css('zIndex',1000); // if autocomplete has misalignment so we are manually setting it
}
}, editrules :{required : true},
formoptions:{rowpos: 1, colpos: 2}
},
........
]
server code :
String term = request.getParameter("term");
List<ArticleDetails> articlelist = prfbo.getPrfArticleName(term); //DB call via BO and DAO class
System.out.println("List Value " +articlelist.size());
JSONArray jsonOrdertanArray = JSONArray.fromObject(articlelist);
System.out.println(jsonOrdertanArray);
out.println(jsonOrdertanArray);
hope some one find it useful.

JQueryAutoComplete Not showing results

I am trying to bind the text box and the JQuery AutoComplete feature. When I checked the Firebug AJAX Request & Response it returns like the following. But the textbox is not showing any items. Could you please advise me, what I am doing wrong? Thanks.
Here is my coding:
$("#<%= TextBox1.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: "/contractors/web_services/wsSM.asmx/SearchDrugs",
type: "POST",
dataType: "json",
data: {
'LocationID': "10543",
'Search': request.term
},
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item.FullDrugName,
id: item.DrugID
}
}))
}
});
},
delay: 1,
minLength: 2,
select: function (event, ui) {
alert(ui.item.id);
}
});
DataType property is representing the type of data that you're expecting back from the server.
you define data type as json but server returns you a xml output. You should change your DataType property to xml
In addition to #fealin's answer, you're going to need to change the way you process the xml response. It doesn't look like you have a d property on the return data, and you also need to look for the correct nodes in the XML structure and pull out their text to build the response array that you return to the widget.
Based on the XML you've provided, it might look something like this:
$("#<%= TextBox1.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: "/contractors/web_services/wsSM.asmx/SearchDrugs",
type: "POST",
dataType: "json",
data: {
'LocationID': "10543",
'Search': request.term
},
success: function (data) {
response($(data).find("Drug").map(function (_, el) {
var $el = $(el);
return {
label: $el.find("FullDrugName").text(),
value: $el.find("DrugID").text()
};
}));
});
},
delay: 1,
minLength: 2,
select: function (event, ui) {
alert(ui.item.id);
}
});
Here's an example that's just using the XML string (without an AJAX request): http://jsfiddle.net/J5rVP/29/

Prevent $.ajaxStart() from being executed during jquery-ui autocomplete

I'm using jquery-ui autocomplete on a page I'm creating. On the same page I have some ajax events going on. During the other ajax events I'm adding an overlay to my page, so that all the links on the website aren't clickable anymore for the user. I don't want that to happen during the autocomplete.
autocomplete:
$(function() {
$( "#search_input" ).autocomplete({
source: '/search_autocomplete/',});
});
ajax:
$.ajax({
url: "/ajax_login/",
login_user: $("#login_user").val(),
password: $("#login_password").val(),
});
ajaxStart:
$("#loading_gif").ajaxStart(function() {
$("#overlay").show();
$(this).show();
});
To prevent the ajaxstart function from being executed during the ajax events where it's not necessary. I add
global:false,
to the corresponding ajaxfunctions. How can I do something similar during the autocomplete without changing the jquery-ui source?
For this you have to omit the shorthand call with source and change the call like this.
$('#search_input').autocomplete({
source: function (request, response) {
var DTO = { "term": request.term };
//var DTO = { "term": $('#search_input').val() };
$.ajax({
data: DTO,
global: false,
type: 'GET',
url: '/search_autocomplete/',
success: function (jobNumbers) {
//var formattedNumbers = $.map(jobNumbersObject, function (item) {
// return {
// label: item.JobName,
// value: item.JobID
// }
//});
return response(jobNumbers);
}
});
}
//source: '/search_autocomplete/'
});
The advantage of this long-hand method is
You can pass more than one parameter. Also the parameter name should not have to be term.
The short-hand notation expects an array of strings. Here you could return an array of objects also.
If you want $.ajax() to work a certain way most of the time but now all the time, then you probably shouldn't change its default behavior.
I recommend creating a function that wraps an ajax request in a function that enables and disables the overlay at the appropriate times. Call this function where you want the overlay to be used, and use plain $.ajax() for your autocomplete.
I would agree that naveen's answer is the best solution. In my case the vast amount of code that would require changing wasn't cost effective as we're in the process of doing a re-write and we needed a short term solution.
You can override the ajax call in jQuery UI, I copied the source for the _initSource function call that handles the AJAX request. Then simply added the global: false to the $.ajax options. The code here is based on jquery-ui 1.9.2, you may have to find the correct source for your version.
$.ui.autocomplete.prototype._initSource = function () {
var array, url,
that = this;
if ( $.isArray(this.options.source) ) {
array = this.options.source;
this.source = function( request, response ) {
response( $.ui.autocomplete.filter( array, request.term ) );
};
} else if ( typeof this.options.source === "string" ) {
url = this.options.source;
this.source = function( request, response ) {
if ( that.xhr ) {
that.xhr.abort();
}
that.xhr = $.ajax({
url: url,
data: request,
dataType: "json",
global: false,
success: function( data ) {
response( data );
},
error: function() {
response( [] );
}
});
};
} else {
this.source = this.options.source;
}
};

Why won't this JqueryUI autocomplete hit its URL?

I'm wiring the following method to my document.ready function. However, the "myAutoCompleteURL.aspx" URL is never being accessed (I have a breakpoint on the page, and it's never being hit).
Anybody know why this isn't working? I'm new to the UI version of AutoComplete; I had previously only used the jquery-based (deprecated) version.
function myAutoComplete(myTextBox, myLabel, myHidden) {
var myType = $(myLabel).html();
$(myTextBox).autocomplete({
source: function (request, response) {
$.ajax({
type: 'POST',
dataType: 'json',
url: "../myAutoCompleteURL.aspx",
data: { q: request.term, type: myType },
success: function (myData) {
response($.map(myData, function (myItem) {
return { label: myItem.name, value: myItem.name, id: myItem.id }
}));
}
});
},
select: function (event, ui) {
$(myTextBox).val(ui.myItem.name);
$(myHidden).val(ui.myItem.id);
return false;
}
});
}
You can remove the ../ in your url. I used to have the same issue sometime ago.
Secondly have an error function in your ajax call. If it hits the error function, then there is some problem in your data and you need to correct that.
As #GregL mentioned in his comment, that you are using JSON and not application/json :)
Use Firebug and look for what URL is being hit instead. If nothing shows up in the console, then the javascript code is not working at all.

Resources