jQuery UI - Autocomplete with extra params - returned data - json

All,
I've moved on to using the ui autocomplete rather than the plugin, took me a while to figure out extra params based on an example I found here, but that part works.
I'm having problems with dealing with the return data. In the code below I can alert out the title being returned, but I get a drop down of 'UNDEFINED' in the browser.
Thanks in advance.
$('#DocTitle').autocomplete({
source: function(request, response) {
$.ajax({
url: "index.pl",
dataType: "json",
data: {
Title: request.term,
maxRows: 10
},
success: function(data) {
response($.map(data, function(item) {
alert(item.TITLE);
return {
TITLE: item.TITLE
}
}))
}
})
}
});

I am using jquery UI autocomplete as follows and it is working quite fine for me. You may try on the similar lines.
$('input[type=text][name=City]').autocomplete({
source: function(request, response) {
$.getJSON($('input#CitySuggestionsLink').val(), {
term: request.term,
stateId: $('select#StateName option:selected').attr('value')
}, response);
},
search: function() {
// custom minLength
var term = this.value;
if (term.length < 1) {
return false;
}
},
delay: 200,
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
return false;
}
});

Related

autocomplete to populate all values on input focus

I have autocomplete textbox whose values are populated using ajax call which returns json data. This works fine with following code lines.
$("#searchTitle").autocomplete({
source: function (request, response) {
$.ajax({
url: "/umbraco/Surface/MyApp/StartSearch",
type: "POST", dataType: "json",
data: { term: request.term },
success: function (data) {
debugger
response($.map(data, function (item) {
debugger
return { label: item.Cat_Name };
}));
}
});
},
messages: { noResults: "", results: "" },
minLength: 0
});
But this function gets called when user type something. Now, I want that when input is focused, all the values from response should be shown in autocomplete. How can I trigger the same?
You can achieve by using search event of autocomplete on focus of input.
For example
$( "#searchTitle" ).focus(function() {
// make sure you put space between double quote
$( "#searchTitle" ).autocomplete("search", " " );
});

jquery validation onSubmit ajax post JSON response

I have a very complicated post using jquery validation and an AJAX post that gets a JSON response back from the server and puts it in a jqGrid... But it seems as though my onsuccess is never being called at any point...
$(document).ready(function () {
$("#formSearchByMRN").validate({
rules: {
MRN: { required: true, minLength: 6 }
},
messages: {
MRN: 'Please Enter a Valid MRN'
},
submmitHandler: function (form) {
e.preventDefault();
animateLoad();
debugger;
var theURL = form.action;
var type = form.methd;
var data = $(this).serialize();
$.ajax({
url: theURL,
type: type,
data: data,
dataType: "json",
success: function (result) {
debugger;
var data = result;
if (data.split(':')[0] == "Empty record") {
$("#list").unblock();
$('#resultDiv').html('<b><p style="color: #ff00ff">' + data + '</p></b>');
setTimeout(function () {
$('#resultDiv').html("");
}, 10000);
}
else {
binddata(data);
}
}
});
return false;
}
});
});
It would seem I never get into the submmitHandler. Event though I manage to get to my server side function and it does return, it prompts my UI to save a file which contains the JSON results...
No good.
Am I going about validating my form before my AJAX post the wrong way? Does anybody have any advice about best practices in validating AJAX posts?
UPDATE... MARK R. This is what I attempted. It seems as though I never get in to the success function... My suspicion is that I am not really posting via ajax, but instead doing a full post. I don't understand why.
$('#submitMRN').click(function () {
$("#formSearchByMRN").validate({
rules: {
MRN: { required: true, minLength: 6 }
},
messages: {
MRN: 'Please Enter a Valid MRN'
}
});
if ($('#submitMRN').valid()) {
$("#list").block({ message: '<img src="../../Images/ajax-loader.gif" />' });
$.ajax({
url: $('#submitMRN').action,
type: $('#submitMRN').method,
data: $('#submitMRN').serialize(),
dataType: "json",
success: function (result) {
debugger;
var data = result;
if (data.split(':')[0] == "Empty record") {
$("#list").unblock();
$('#resultDiv').html('<b><p style="color: #ff00ff">' + data + '</p></b>');
setTimeout(function () {
$('#resultDiv').html("");
}, 10000);
}
else {
binddata(data);
}
}
});
}
});
$('#SubmitButton').click(function (){
//Check that the form is valid
$('#FormName').validate();
//If the Form is valid
if ($('#FormName').valid()) {
$.post(...........
}
else {
//let the user fix their probems
return false;
}
});//$('#SubmitButton').click(function (){

autocomplete jquery.get json doesn't complete

I'm having trouble with autocomplete, usign JSON data.
I'm getting the right response from the callback, but the autocomplete doesn't work properly. For example, when I type "Lon" I get this response:
[{\"value\":\"Dijon, (DIJ)\",\"code\":\"DIJ\"},{\"value\":\"Longview, (GGG)\",\"code\":\"GGG\"},{\"value\":\"Long Island, (HAP)\",\"code\":\"HAP\"},{\"value\":\"Islip, (ISP)\",\"code\":\"ISP\"},{\"value\":\"Long Banga, (LBP)\",\"code\":\"LBP\"},{\"value\":\"Londrina, (LDB)\",\"code\":\"LDB\"},{\"value\":\"Londonderry, (LDY)\",\"code\":\"LDY\"},{\"value\":\"Long Beach, (LGB)\",\"code\":\"LGB\"},{\"value\":\"Long Lellang, (LGL)\",\"code\":\"LGL\"},{\"value\":\"Long Akah, (LKH)\",\"code\":\"LKH\"},{\"value\":\"Londra, (All airports - LON)\",\"code\":\"LON\"},{\"value\":\" - Londra, Gatwick Arpt (LGW)\",\"code\":\"LGW\"},{\"value\":\" - Londra, London City Arpt (LCY)\",\"code\":\"LCY\"},{\"value\":\" - Londra, Stansted Arpt (STN)\",\"code\":\"STN\"},{\"value\":\" - Londra, London Biggin Hill Arpt (BQH)\",\"code\":\"BQH\"},{\"value\":\" - Londra, Heathrow (LHR)\",\"code\":\"LHR\"}]
But my autocomplete just adds Longview and Long Island.
The tricky thing is that after I keep typing "Lond", the autocomplete works perfect, I delete the "d", the autocomplete works perfect, it completes all the data from above.
Where do I go wrong...?
Here's my code:
$("#destination2").keyup(function(){
var term = $("#destination2").val();
//var query_type = $("#form_type").val();
jQuery.get('http://online.bileteavion.com.ro/q_travel_online_api/misc/hotels.autocomplete.php?query_type=flight&term='+term, function(data) {
data = eval('['+data.responseText.split('[')[1].split(']')[0]+']');
var source = $.map(data, function(item) {
return {
label: item.value,
value: item.value,
id: item.id,
iata: item.iata
}
});
$("#destination2").autocomplete({
source: source,
minLength: 3,
search: function(event, ui) {
$('#loading-spinner').show();
},
change: function(event, ui) {
//console.log(ui.item);
if( !ui.item ) {
$(this).val("");
$("input[name='cityId']").val("");
$("input[name='destinationIataCode']").val("");
$("input[name='destination']").val("");
}
},
open: function() {
$('#loading-spinner').hide();
},
select: function(event, ui) {
$("input[name='cityId']").val(ui.item.id);
$("input[name='destinationIataCode']").val(ui.item.iata);
$("input[name='destination']").val(ui.item.value);
$(this).blur();
}
});
}
);
});
jquery.autocomplete is not a function to call every single time you want to display the autocomplete dialog.
You should call jquery.autocomplete only once during initializion, to equip your input field with a full mechanism which allows autocompleting - and which will take care of the "keyup" event.
To achieve what you need, you should use a callback with the source option.
Here is how :
Instead of :
$("#destination2").keyup(function(){
...
jquery.get(<url>, function(data){
var source = ...
$("#destination2").autocomplete({
source: source
minLength: ...
search: ...
open: ...
select: ...
})
})
})
You should write :
$("#destination2").autocomplete({
source: function(request, response){
//request is an obj containing infos on what is typed
//response is a callback, which should be called if you want to display hints
jQuery.get(url + request.term, function(data){
var source = ...
response(source);
})
}
minLength: ...
search: ...
open: ...
select: ...
})
You should check the Remote JSONP datasource from the docs.
I use this in my site. Works quite well.
$("#id").autocomplete({
source: function (request, response) {
$.ajax({
url: 'http://online.bileteavion.com.ro/q_travel_online_api/misc/hotels.autocomplete.php',
dataType: "json",
data: {
//values to pass to server. in your case: query_type & term
term: request.term,
query_type: 'flight'
},
success: function (data) {
response($.map(eval(data), function (item) {
return {
//map values as you previously did
label: item.value,
value: item.value,
id: item.id,
iata: item.iata
}
})
);
}
})
},
minLength: 3,
search: function(event, ui) {
$('#loading-spinner').show();
},
change: function(event, ui) {
//console.log(ui.item);
if( !ui.item ) {
$(this).val("");
$("input[name='cityId']").val("");
$("input[name='destinationIataCode']").val("");
$("input[name='destination']").val("");
}
},
open: function() {
$('#loading-spinner').hide();
},
select: function(event, ui) {
$("input[name='cityId']").val(ui.item.id);
$("input[name='destinationIataCode']").val(ui.item.iata);
$("input[name='destination']").val(ui.item.value);
$(this).blur();
}
});

Retrieving search data from database using jQuery autocomplete?

I am using jQuery UI Autocomplete plugin for better data input in my ASP.NET web application.
http://jqueryui.com/demos/autocomplete/
However, I think I have somehow lost in this plugin.
I would like to ask what I should do in order to use this autocomplete function with the data retrieve from database?
I expect Ajax should be used for the real-time search,
but I have no idea how it can be done after looking at the demo in the website above.
Thanks so much.
Update:
Here is the code I have tried, doesn't work, but no error in firebug too.
$('#FirstName').autocomplete({
source: function (request, response) {
$.ajax({
url: "/Contact/FirstNameLookup?firstName=",
type: "POST",
data: {
"firstName": $('#FirstName').val()
},
success: function (data) {
response($.map(data, function (item) {
return {
label: item.FirstName,
value: item.FistName
}
}));
}
});
}
});
You need to create an action that does the lookup and returns the result as a JsonResult
e.g.
public ActionResult FirstNameLookup(string firstName)
{
var contacts = FindContacts(firstname);
return Json(contacts.ToArray(), JsonRequestBehavior.AllowGet);
}
I'm not sure if this will solve all your problems but here are a couple of edits you can make.
you don't need the "?firstname=" part of the url since you are using the data parameter for you ajax request.
rather than grabbing your search term with $('#FirstName').val(), try using the term property of the request object (request.term).
for example:
$('#FirstName').autocomplete({
source: function (request, response) {
$.ajax({
url: "/Contact/FirstNameLookup",
type: "POST",
data: {
"firstName": request.term
},
success: function (data) {
response($.map(data, function (item) {
return {
label: item.FirstName,
value: item.FistName
}
}));
}
});
}
});

$jQuery Tree from json data ---> .live is killing me

I'm trying to build a tree from json data, this data are loaded on demand from php files. My problem is that i can't find a way to get to lvl 3 ;). Here is my code:
$(document).ready(function()
{
//Get the screen height and width
var Height = $(document).height()/2;
var Width = $(window).width()/2;
$("#div1").hide();
$("#div2").hide('slow');
$.ajax(
{
type: 'post',
async: true,
url: "getparents.php",
data: {'id' : 12200},
dataType: "json",
cache: false,
beforeSend: function ()
{
//Show the Loading GIF at centered position
$('#loading').css({'top': Height, 'left': Width}).show();
},
success: function(json_data)
{
$("#div1").empty().show();
$('<ul class="parentContainer"></ul>').appendTo("#div1");
$.each(json_data, function(key, object)
{
$('<li id="node">'+object.name+'</li>').data('id', object.id).appendTo(".parentContainer");
if (object.childbool == true)
{
$('li:last').addClass('childfull')
}
});
},
error: function ()
{
$('#loading').hide();
alert('Something Went Wrong with the Loading please hit back in a minute');
},
complete: function ()
{
$('#loading').hide();
}
});
function getChild(id, node)
{
$.ajax(
{
type: 'post',
async: true,
url: "getchilds.php",
data: {'id' : id},
dataType: "json",
cache: false,
beforeSend: function ()
{
$('#loading').show();
},
success: function(json_data)
{
$('<ul class="childContainer"></ul>').appendTo(node);
$.each(json_data, function(key, object)
{
$('<li id="node">'+object.name+'</li>').data('id', object.id).appendTo(".childContainer");
if (object.childbool == true)
{
$('li:last').addClass('childfull')
}
});
},
error: function ()
{
$('#loading').hide();
alert('Something Went Wrong with the Loading please hit back in a minute');
},
complete: function()
{
$('#loading').hide();
}
});
}
$("li.childfull, li.openchildfull").live('click',function()
{
if ($('li.childfull'))
{
var node = $(this);
var id= $(this).data('id');
$(node).html(getChild(id, node));
$(node).removeClass().addClass('openchildfull');
}
else
{
$(node).removeClass().addClass('childfull');
$(node).children().remove();
}
});
});
I think .live is killing me. I get my parents on load; when I click on one I get its children ALL pretty and well, but when I click on a child to get its children I get a very funny behavior. I get its children correctly indented but with no class="childfull" and I get an other copy of them not properly indented but with correct class.. I don't know what is going wrong... Any ideas/corrections are welcome.
P.S: You don't want me to describe to you what happens when I click on the messed up 3rd lvl childfull :P.
Instead of going through the headache of building your own tree, have a look at the jstree plugin. You can pass different formats to it, including json. It allows for complete customization and allows infinite(possible :p) child levels.