Pass variable by Post method from JQuery UI Autocomplete to PHP page - jquery-ui

I have two JQuery UI autocomplete input fields.
When an option is selected in the first one, the value of the selection will be used as condition for a database query that will send the source data for the second autocomplete field.
My problem is how do I send the value of the first selection to the PHP page via Post method?
The code so far is shown below (this code is from a tutorial which used the GET method; but I want to use Post):
<script>
$("input#divisions").autocomplete ({
//this is the first input
source : [
{ value: "81", label: "City1" },
{ value: "82", label: "City2" },
{ value: "83", label: "City3" } ],
minLength : 0,
select: function(event, ui) {
$('#divisions').val(ui.item.label);
return false;
},
focus: function(event, ui){
$('#divisions').val(ui.item.label);
return false;
},
change: function(event, ui){
//the tutorial has this value sent by variables in the URL; I want the selection value sent by POST. How can I change this?
c_t_v_choices = "c_t_v_choices.php?filter=" + ui.item.value;
$("#c_t_v").autocomplete("option", "source", c_t_v_choices);
}
}).focus (function (event)
{
$(this).autocomplete ("search", "");
});
$("#c_t_v").autocomplete({
source: "",
minLength: 2,
select: function(event,ui){
//$('#city').val(ui.item.city);
}
});
</script>
Can anyone please help?
Dont hesitate to let me know if you have any questions.

The solution I found for this is to use AJAX to create the source when a selection is made in the first autocomplete.
Sample code can be found here: https://stackoverflow.com/questions/12715204/assigning-source-for-jquery-autocomplete

Related

triggering JQuery 'autocomplete' in a secondary textarea

We currently have two HTML textareas 'tinput'(primary) and 'toutput' (secondary) where we mimic the input in the primary to be reflected in the secondary as if someone is really typing in the secondary. The idea is to trigger an 'autocomplete' (over ajax) on the secondary. We have this working but not optimally.
We have attached a JQuery UI 'Autocomplete' (JQAC) to the secondary with a minLength:3 set. You may know that, normally, after 3 characters have been entered, JQAC 'buffers' the char entries thereon after and doesn't make an ajax call for every char that has been entered. Which is ideal.
However, with our secondary mimicking we have subverted this behavior, unfortunately, where after the 3rd char entry a JQAC ajax call is being made for every char after-- which is not optimal. We know why but don't know how to get around it. We believe we've subverted this because we are calling
$('#tinput').autocomplete('search',$('#tinput').val())
in the secondary's key handle, which by JQAC's documentation forces an ajax call.
To summarize, we need the secondary, that has JQAC attached to it, to behave as if someone were really typing into it and the JQAC behaving normally.
Here is JS for what we have as our char input mimic handling(we've changed variable names for this post so please ignore typos):
$("#tinput").on('input', function (e) {
$("#toutput").val($("#tinput").text());
var newEvent = jQuery.Event("keypress");
newEvent.which = e.which; // # Some key code value
$("#toutput").trigger(newEvent);
});
$("#toutput").keypress(function(e) {
$("#toutput").autocomplete('search',$("#toutput").val());
});
$( "#tinput" ).autocomplete({
appendTo: "#modalparent",
source: function( request, response ) {
$.ajax({
url: "https://xxxxxx",
type: "POST",
dataType: "json",
data: JSON.stringify({ "ourterm": request.term}),
success: function( data ) {
response( $.map( data.data.suggestions, function( item ) {
return {
label: item,
value: item
};
}));
}
});
},
minLength: 3,
select: function( event, ui ) {
// console.log( ui.item ?
// "Selected: " + ui.item.label :
// "Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
Any thoughts would be appreciated. Thanks!
We have found an elegant solution. It was a minor modification to our original.
change the trigger event by the primary to 'input' instead of the original 'keypress'.
remove the handler for the secondary.
here is the updated JS:
$("#tinput").on('input', function (e) {
$("#toutput").val($("#tinput").text());
var newEvent = jQuery.Event("input");
newEvent.which = e.which; // # Some key code value
$("#toutput").trigger(newEvent);
});
and delete:
//$("#toutput").keypress(function(e) {
// $("#toutput").autocomplete('search',$("#toutput").val());
// });
DONE.

Tooltip using jquery ui

Its my first time using the tooltip and have done a lot research on it. I used the jquery website to get most of the information. I intend my tooltip to show dynamic data when a mouse clicks the hyperlink. I added the title to my link and have this code below:
var t = 1000;
$(document).tooltip({
content: '... waiting on ajax ...',
open: function(evt, ui) {
var elem = $(this);
$.ajax({ type: "POST",url:'/GetTooltip/', data: 80140}).always(function() {
elem.tooltip('option', 'content', 'Ajax call complete');
});
setTimeout(function(){
$(ui.tooltip).hide('destroy');
}, t);},
position: {
my: "center bottom-20",
at: "center top",
using: function( position, feedback ) {
$( this ).css( position );
$( "<div>" )
.addClass( "arrow" )
.addClass( feedback.vertical )
.addClass( feedback.horizontal )
.appendTo( this );
}
}
});
I am not fully knowledgeable with the syntax of the ajax call in reference to the always function and how to get the data to show on my tooltip. the GetTooltip returns JSON data, I just want to post to the GetTooltip script and the returned data to show on my tooltip. At the moment my ajax is posting nothing.
Regarding your statement that you are not fully knowledgeable with
always function: the always(function(data|jqXHR, textStatus, jqXHR|errorThrown) { }); is always executed after the ajax request was executed. For more see the documentation deferred.always() Please look also at jqXHR.always(function(data|jqXHR, textStatus, jqXHR|errorThrown) { })
get the returned data to show on the tooltip - see the example in the fiddle
You can find many other answers on stackoverflow. Take a look at this fiddle and let me know if you need more help.
Updated fiddle 2
If have updated the fiddle. You can pass values from the parameters that are returned from the ajax callback. This is a simple wrapper around the ajax call:
function callAjax(elem){
$.ajax({ url: '/echo/json/',
type: 'POST',
contentType:"application/json; charset=utf-8",
dataType:"json",
data: { json: JSON.stringify({ text: 'some text'})}
}).always(
function(data,textStatus, errorThrown)
{
elem.tooltip('option', 'content'
, 'Ajax call complete. Result:' + data.text);
});
}
I am using JSON.stringify(...) above to create a Json-String. This function may be not present in all browsers. So if you run into troubles please use a current chrome / chromium browser to test it.
So you can use the wrapper function inside the tooltip():
$('#tippy').tooltip({
content: '... waiting on ajax ...',
open: function(evt, ui) {
var elem = $(this);
callAjax(elem);
} // open
});
Above you can see that the always method calls an anonymous function with 3 parameters (data, textStatus, errorThrown). To pass the reply from the ajax call you can use data. Above i am only passing a simple object with the propert text. To access it you can use data.text

jQGrid + jQueryUI Autocomplete + combobox automatically open on focus

I'm sure I'm missing something very simple on this one. After banging my head against the desk (literally) for a couple of days now, I submit myself to the mercy of the stack:
I'm using jQuery UI Autocomplete as a combobox in my jQGrid (I know! I've already looked for the solution elsewhere to no avail!). I would like the dropdown to open when I access the cell for editing through the onSelectRow event in jqGrid. Basically, I want to do exactly what is discussed here:
Open jQuery UI ComboBox on focus
and demo'd here:
http://jsfiddle.net/gEuTV/
The only difference is that I need it in jqGrid. I've tried the code below which I (mistakenly) through would trigger the combobox to appear when the row is focused, but the combobox doesn't appear on focus of the row in the onSelect event. I have a sneaking suspicion that I'm just putting the following code in the wrong spot, but I've tried it everywhere I can think of:
$("#"+id+"_usr_validation","#list2").bind("focus", function () {
this.value = '';
$(this).autocomplete("search", '');
Here's my complete code including the grid:
$(function(){
var lastsel;
$("#list2").jqGrid({
url: 'php_includes/uploadgrid.php',
datatype: "json",
mtype: 'GET',
colNames:[
'User Value',
'Translated Value',
'User Validation,
],
colModel:[
{name:'usr_value',index:'usr_value', sortable:'true', width:60, align:"center", editable:false},
{name:'translated_value',index:'translated_value', sortable:'true', width:60, align:"center", editable:false},
{name:'usr_validation',index:'usr_validation', sortable:'true', width:60, align:"center", editable:true}
],
pager: '#pager2',
rowNum: 1000,
scroll: true,
gridview: true,
viewrecords: false,
height: 'auto',
hidegrid: false,
autowidth: true,
pgbuttons: false,
pginput: false,
forceFit: true,
emptyrecords: "No record was loaded",
onSelectRow: function(id){
if(id && id==lastsel){
$("#list2").jqGrid('editRow',id,true,autocomp,'','','',selectNone);
} else {
if(id && id!==lastsel){
$("#list2").jqGrid('saveRow',lastsel);
$("#list2").jqGrid('editRow',id,true,autocomp,'','','',selectNone);
lastsel=id;
}
}
},
editurl: '/php_includes/jqGridCrud.php',
});
jQuery("#list2").jqGrid('navGrid',"#pager2",{edit:false, search:false, del:false, add:false})
function selectNone(){
$("#list2").jqGrid('resetSelection');
}
//this function de-selects all previously accessed rows
function autocomp(id) {
var term2 = $("#list2").jqGrid('getCell',id,'usr_value');
$("#"+id+"_usr_validation","#list2")
.autocomplete({
source: function(request, response) {
$.ajax({
url: "/php_includes/Autocomplete.php",
dataType: "json",
data: {
term : request.term,
term2 : term2,
},
success: function(data) {
response(data);
}
});
},
minLength: 0,
select: function(event, ui) {
$("#list2").val(ui.item.id);
},
});
$("#"+id+"_usr_validation","#list2").bind("focus", function () {
this.value = '';
$(this).autocomplete("search", '');
});
}
});
You should change 'User Validation, to 'User Validation' and remove trailing commas in different places of your code (like from editurl: '/php_includes/jqGridCrud.php',} and close which are syntax errors in JavaScript, but ignored in many, but not all web browsers).
UPDATED: One more problem is that the focus on the editing field will be set before oneditfunc will be called, so the "focus" event can not be triggered. As a workaround you can trigger "focus" event directly after the .bind("focus", ....
See your modified demo here.

How do I pass an extra parameter to Jquery Autocomplete field?

I'm using the JQuery Autocomplete in one of my forms.
The basic form selects products from my database. This works great, but I'd like to further develop so that only products shipped from a certain zipcode are returned. I've got the backend script figured out. I just need to work out the best way to pass the zipcode to this script.
This is how my form looks.
<form>
<select id="zipcode">
<option value="2000">2000</option>
<option value="3000">3000</option>
<option value="4000">4000</option>
</select>
<input type="text" id="product"/>
<input type="submit"/>
</form>
And here is the JQuery code:
$("#product").autocomplete
({
source:"product_auto_complete.php?postcode=" + $('#zipcode').val() +"&",
minLength: 2,
select: function(event, ui){
//action
}
});
This code works to an extent. But only returns the first zipcode value regardless of which value is actually selected. I guess what's happening is that the source URL is primed on page load rather than when the select menu is changed. Is there a way around this? Or is there a better way overall to achieve the result I'm after?
You need to use a different approach for the source call, like this:
$("#product").autocomplete({
source: function(request, response) {
$.getJSON("product_auto_complete.php", { postcode: $('#zipcode').val() },
response);
},
minLength: 2,
select: function(event, ui){
//action
}
});
This format lets you pass whatever the value is when it's run, as opposed to when it's bound.
This is not to complicated men:
$(document).ready(function() {
src = 'http://domain.com/index.php';
// Load the cities straight from the server, passing the country as an extra param
$("#city_id").autocomplete({
source: function(request, response) {
$.ajax({
url: src,
dataType: "json",
data: {
term : request.term,
country_id : $("#country_id").val()
},
success: function(data) {
response(data);
}
});
},
min_length: 3,
delay: 300
});
});
jQuery("#whatJob").autocomplete(ajaxURL,{
width: 260,
matchContains: true,
selectFirst: false,
minChars: 2,
extraParams: { //to pass extra parameter in ajax file.
"auto_dealer": "yes",
},
});
I believe you are correct in thinking your call to $("#product").autocomplete is firing on page load. Perhaps you can assign an onchange() handler to the select menu:
$("#zipcode").change(resetAutocomplete);
and have it invalidate the #product autocomplete() call and create a new one.
function resetAutocomplete() {
$("#product").autocomplete("destroy");
$("#product").autocomplete({
source:"product_auto_complete.php?postcode=" + $('#zipcode').val(),
minLength: 2,
select: function(event, ui){... }
});
}
You may want your resetAutocomplete() call to be a little smarter -- like checking if the zip code actually differs from the last value -- to save a few server calls.
This work for me. Override the event search:
jQuery('#Distribuidor_provincia_nombre').autocomplete({
'minLength':0,
'search':function(event,ui){
var newUrl="/conf/general/provincias?pais="+$("#Distribuidor_pais_id").val();
$(this).autocomplete("option","source",newUrl)
},
'source':[]
});
Hope this one will help someone:
$("#txt_venuename").autocomplete({
source: function(request, response) {
$.getJSON('<?php echo base_url(); ?>admin/venue/venues_autocomplete',
{
user_id: <?php echo $user_param_id; ?>,
term: request.term
},
response);
},
minLength: 3,
select: function (a, b) {
var selected_venue_id = b.item.v_id;
var selected_venue_name = b.item.label;
$("#h_venueid").val(selected_venue_id);
console.log(selected_venue_id);
}
});
The default 'term' will be replaced by the new parameters list, so you will require to add again.
$('#product').setOptions({
extraParams: {
extra_parameter_name_to_send: function(){
return $("#source_of_extra_parameter_name").val();
}
}
})
$('#txtCropname').autocomplete('Handler/CropSearch.ashx', {
extraParams: {
test: 'new'
}
});

JQuery UI autocomplete change event - resetting selection ID

I'm using the AutoComplete UI widget for a form to allow users to type in a customer name. The idea is that they can either select an existing customer and populate other fields in the form, or they can free-type a new customer to be created. When a user selects an existing customer, I use the select event to populate a hidden input to store the ID associated with that customer.
The problem I'm having is if a user first selects a customer from the list but then goes in and edits the text, in effect creating a new customer, I need to be able to clear out that hidden input ID value.
I referred to this SO question and created the following code:
$(function() {
$("#customerName").autocomplete({
source: "/Customers/CustomerListJSON",
minLength: 2,
select: function(event, ui) {
$("#customerId").val(ui.item ? ui.item.Id : "");
},
change: function(event, ui) {
try {
$("#trace").append(document.createTextNode(event.originalEvent.type + ", "));
if (event.originalEvent.type != "menuselected")
$("#customerId").val("");
} catch (err) {
$("#customerId").val("");
}
}
});
});
The problem is that the change event is fired on blur, so if a user selects a customer, the hidden input value is populated, but as soon as they move focus off the input box it's cleared right away. However, if I exclude the blur event from the event.originalEvent.type test, then the hidden field's value never gets reset in the original scenario where a user edits a previously-selected value.
Has anyone had to tackle this before, and if so can you offer some guidance on how I can manage that hidden input's value so it's populated only when an item is selected from the list and cleared with any other value?
Looks like I solved this pretty quickly on my own. Referring to the JQuery UI wiki, the ui item in the change event is the same one in the select event, so I can modify my code to read like this:
$(function() {
$("#customerName").autocomplete({
source: "/Customers/CustomerListJSON",
minLength: 2,
select: function(event, ui) {
$("#customerOrganizationId").val(ui.item ? ui.item.Id : "");
},
change: function(event, ui) {
$("#customerOrganizationId").val(ui.item ? ui.item.Id : "");
}
});
});
There's no need to test for the event, just for whether there is an item in the ui argument. The ID setting in the select event is probably redundant, but to be safe I'm going to keep both.
$(function() {
$("#customerName").autocomplete({
source: "/Customers/CustomerListJSON",
minLength: 2,
select: function(event, ui) {
$("#customerId").val(ui.item ? ui.item.Id : "");
},
change: function(event, ui) {
try {
$("#trace").append(document.createTextNode(event.originalEvent.type + ", "));
if (event.originalEvent.type != "menuselected")
$("#customerId").val("");
} catch (err) {
$("#customerId").val("");
}
}
});
});

Resources