Parsing in jQuery Autocomplete - php

I have generated some data from a MySQL query that I want to do two things with. The data is an array of names and IDs.
First I want to use the name portion for a jQuery autocomplete, so that the name is what you can select in the field.
Secondly, I want to fire on select in the autocomplete something that will place the ID of the selected item into a hidden field.
Here is my JQuery:
$("#contact").autocomplete(
source: function(request, response){
$.ajax({
url: "ajax/grabdata.php?",
type: "GET",
data: request,
success: function (data) {
response($.map(data, function (el) {
return {
label: el.item.name,
value: el.item.id
};
}));
}
});
},
width: 260,
matchContains: true,
selectFirst: false,
select: function(event, ui){
$('#contact').val(ui.label);
$('#id').val(ui.value);
}
});
Here is how I grabbed the data in PHP (grabdata.php):
$sql = "SELECT DISTINCT contacts.id, contacts.firstname, contacts.lastname FROMcontacts WHERE (firstname LIKE '%$q%' OR lastname LIKE '%$q%')";
$rsd = mysql_query($sql);
while($rs = mysql_fetch_array($rsd)) {
$kdata[] = array(
"name" => $rs['firstname'].' '.$rs['lastname']."\n",
"id" => $rs['ID']."\n",
);
$dataset[] = $kdata;
}
I can get the data, but I am having trouble parsing it into what I want. The name should be selectable in the autocomplete field, and the ID should be filled in based on the name chosen.

As far as I can see, you are not using the select method parameters as you should:
select: function(event, ui){
$('#contact').val(ui.item.label);
$('#id').val(ui.item.value);
}
You are missing the ".item". Check the documentation: http://jqueryui.com/autocomplete/#remote

Related

Datatables - filter sql query by bootstrap-datepicker values

I have 2 bootstrap datepickers(#start,#end) and a Datatable which returns 150.000 rows from MS SQL Server via PHP.I want by default the start date to be 7 days earlier nad the end date to be Today.
I need to find a way to filter the Sql Query (in a PHP file) with WHERE condition between #start and #end datepicker values.If i use no filter the returned JSON is 60 MBs which freezes the browser and consequently i can't even filter the Datatable in the client.
I have already used $.fn.dataTable.ext.search.push to filter the Datatable on the client and it works ,but i want to filter the JSON output from the Sql Query before it returns to the browser.
How can i dynamically pass these date values via ajax.url in the Sql Query which is in the backend PHP file?
var curdate = moment().subtract(7, 'day').toDate();
$( '#end' ).datepicker( 'setDate', new Date() );
$( '#start' ).datepicker( 'setDate', curdate );
var start = $('#start').val();
var end = $('#end').val();
$("#start").datepicker({ language: 'el', autoclose: true,
onchangeDate: function () {
var start = $('#start').val();
table.ajax.url('queries.php?q=employees_full&start='+start'&end='+end); //do i miss a + here??
//table.ajax.reload();
table.draw(); }});
$("#end").datepicker({ language: 'el', autoclose: true,
onchangeDate: function () {
var end = $('#end').val();
table.ajax.url('queries.php?q=employees_full&start='+start'&end='+end); //do i miss a + here??
//table.ajax.reload();table.draw(); }});
$('#start, #end').change(function () {
//table.ajax.url('queries.php?q=employees_full&start='+start+'&end='+end);
// table.ajax.reload();
table.draw();
});
1)What is the difference between table.ajax.reload() and table.draw ?
2)i also get an error in JSON output"Conversion failed when converting date and/or time from character string." .Probably the #start datepicker value is undefined,i don't know why??
3)Is the order of the commands right?
4)The dates in the Datepicker are in Format dd/mm/yyy but in the Sql Query queries.php?q=employees_full are in Format yyyy-mm-dd.I use prepared statements and have used the following:
(CONVERT(date,SUBSTRING(CONVERT(varchar, ?, 100), 4, 3) +SUBSTRING(CONVERT(varchar, ?, 100), 1, 3)+SUBSTRING(CONVERT(varchar, ?, 100), 7, 4)))
AND
$stmt = sqlsrv_prepare( $conn, $sql , array(&$_GET["start"],&$_GET["start"],&$_GET["start"]));
The Datatable is :
var table = $('#example').DataTable({
//"serverSide": true,
"ajax" : { url: 'queries.php?q=employees_full&start='+start'&end='+end ,
dataType: "json",
dataSrc: '' },
"order": [[ 5, "desc" ]],
"autoWidth": true,
"deferRender": true ,
"columns": [
{ "data": "username", "title": "Username" }]
});
EDIT 15/3/19
After a lot of research,i ended up to this.
I initialize the bootstrap datepickers and with the ajax.data option i pass the parameters(date objects) to the php Sql Query.
1)Is it better to pass the parameters as date objects instead of strings so that the conversion and comparison in the Sql Query is easier?
2)Should the initialisation of the Datepickers be before or after the Datatable?
3)Should i use 2 events .change and .on('changedate') for the datepickers so that both values to have been set before the initialisation of the datatable?
When i load the page , I get error : input1 is not defined
and after that when i pick different dates,i get TypeError: table is undefined.
I still can't find the right order of the commands i should use.
Any help would be appreciated!
var curdate = moment().subtract(7, 'day').toDate();
$("#start,#end").datepicker({ language: 'el', autoclose: true});
$( '#end' ).datepicker( 'setDate', new Date() );
$( '#start' ).datepicker( 'setDate', curdate );
$('#start, #end').datepicker({ language: 'el', autoclose: true}).change(function () {
//var thisval = this.value; //this.val--> undefined
var start= $( '#apo' ).datepicker( 'getUTCDate' );// returns datetime object
var end= $( '#ews' ).datepicker( 'getUTCDate' );// returns datetime object
var input1={ startdate: $( '#start' ).datepicker( 'getUTCDate' ),
enddate: $( '#end' ).datepicker( 'getUTCDate' ) };
//table.ajax.url("queries.php?q=employees_full"); //do i need this?
//table.ajax.reload(); //or table.draw();
});
var table = $('#example4').DataTable({
"ajax" : { url: "queries.php?q=employees_full" ,
dataType: "json",
dataSrc: '' ,
data: input1 },
......});
In the PHP Sql Query queries.php?q=employees_full i prepare the statement with
... WHERE alldates.alldate >= (CONVERT(date, ?)) and alldates.alldate <= (CONVERT(date, ?))
and
$stmt = sqlsrv_prepare( $conn, $sql , array(&$_POST["startdate"],&$_POST["enddate"]));
What am i missing?

Laravel- datatables inline editing and use autocomplete for multitables

I have a complicated problem, I have a table that contains data as Im using datatable, table Checks have relationship with other table Vendors
what I want just when click on cell vendor_id make it editable and use autocomplete function to fill or edit current data.
I want table to be editable like this example
https://editor.datatables.net/examples/inline-editing/simple
my table screenshot
Check table:
details
description
vendor_id
Vendors table:
vendor_id
vendor_name
now the name of vendor appears in the datatable but dont know why its inside brackets and "" [{"vendor_name":"Raul"}]
so All I want just to show vendor_name and edit it using autocomplete and to store it in the Check Table by storing vendor_id not vendor name
Ajax
var oTable = $('#users-table').DataTable({
dom: 'flBrtip',
stateSave: true,
paging: true,
pagingType: 'simple_numbers',
processing: true,
serverSide: true,
ajax: {
url: 'custom-filter-data',
data: function(d) {
d.start_date = $('input[name=start_date]').val();
d.end_date = $('input[name=end_date]').val();
}
},
columns : [
{data: 'details', name: 'details'},
{data: 'description', name: 'description'},
{data: 'vendor_id',name:'vendor_id'},
{data: 'category_id',name: 'category_id'},
],
pageLength: 10,
});
oTable.draw();
Controller
public function getCustomFilterData()
{
$arrStart = explode("/", Input::get('start_date'));
$arrEnd = explode("/", Input::get('end_date'));
$start = Carbon::create($arrStart[2], $arrStart[0], $arrStart[1], 0, 0, 0);
$end = Carbon::create($arrEnd[2], $arrEnd[0], $arrEnd[1], 23, 59, 59);
$orders = Checks::between($start, $end);
return Datatables::of($orders)->editColumn('vendor_id', function ($user)
{
$vendor =Vendors::select('vendor_name')->where('vendor_id',$user->vendor_id)->get();
return ( $vendor);
}) ->make( TRUE );
}
You're using ->get(); which returns and array and thus the []
If you only want one column (vendor_name) write it like this.
$vendor =Vendors::where('vendor_id',$user->vendor_id)->first();
return $vendor ? $vendor->vendor_name : '';
Explanation of get and first differences: https://laravel.com/docs/5.5/queries#retrieving-results

jQuery UI AutoComplete with multiple cells

I need some help with jQuery UI autocomplete function.
I have one cell which has class, and I have a working autocomplete in it right now.
$("[class*='enari']").autocomplete({
source: "getproductnow.php",
autoFocus: true,
minLength: 2,
dataType: "json",
select: function(event, ui) {
$('#tuote').val(ui.item.value);
},
open: function(event, ui){
$("ul.ui-autocomplete li a").each(function(){
var htmlString = $(this).html().replace(/</g, '<');
htmlString = htmlString.replace(/>/g, '>');
$(this).html(htmlString);
});
}
});
Where the problem comes is the situation where script adds by "document.createElement('div');" a new input field which has same name and autocomplete is not anymore working.
I need to have autocomplete working with "running numbers (1,2,3,4,5,6 and so on...)". Is it even possible and how?
Sorry for my rough language and thank you for your answers!

Assign data to a variable in jquery

I have this code,
$(function() {
//var asd = '<?php $regions_list_full; ?>';
var projects = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
//icon: "jquery_32x32.png"
},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
//icon: "jqueryui_32x32.png"
},
{
value: "sizzlejs",
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine",
//icon: "sizzlejs_32x32.png"
}
];
$( "#find" ).autocomplete({
minLength: 0,
source: projects,
focus: function( event, ui ) {
$( "#find" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#find" ).val( ui.item.label );
//$( ".module h1" ).val( ui.item.value );
$(":header.title").html(ui.item.value);
//$( "#project-description" ).html( ui.item.desc );
//$( "#project-icon" ).attr( "src", "images/" + ui.item.icon );
return false;
}
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
.appendTo( ul );
};
});
actually this is from the autocomplete of jQueryUI, and I have an array of values which are fetched from the database. What I want is to replace my values into the var projects =[{value:asd}] such that my suggestions of the autocomplete will be the data from the database. How would I do this?
You don't want to use source: projects you probably want to define a function for the source using an AJAX call like this
$( "#search_address" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: '/path/to/script',
dataType: 'json',
data: 'whatever you need here', // i.e. term value
dataFilter: function (data, type) {
// do whatever you need to here to change data into proper autocomplete array format
// if JSON data is already in correct format you can just do this.
response($parseJSON.(data));
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// handle error here
},
success: function(data) {
// maybe check for case of empty data object here (i.e. successful URL request, but no data returned)
return data;
}
});
}
});
Now you typically want to limit the number of results returned by your API (maybe 10 or 20 records at most), as it is likely a bad UI experience to have 1000 items show up in autocomplete. On a good autocomplete the number of results should decrease dramatically after a few letters have been types in. This also make you script perform much better in that you are only processing a handful of returned records. For the same reason, you may also want to use the minLength property of autocomplete to not even bother starting the request until X number of characters are entered.
Change
source: projects,
to
source: url_to_script
Form which script you'll send your json. See this example. If you see the source code, you'll see that in source property they use source: search.php.
Similarly, you can use your own script path and return a json data from that script, where that data will coming from server.
jQuery autocomplete will send a a querystring along to the url that you provide in the source: url , this query string will be term so remember that , because I don't think autocomplete docs tell you that , then from there you use the term querysting to query the database and send back items that start with term , You do not request every row in the database and store them in javascript variable, that would not make sense - what if there are 2,000,000 entries in the database?

JQueryUI Autocomplete - Trigger on all events

I'm using JQuery UI Autocomplete to pull records from a caller database. This works fine for records that are in the database but I want to improve handling for new records.
For example, if a user chooses a name from a suggestion, I use the return id later in the form. This works fine. If the value is not found in suggestions I am struggling to trigger the script since it is currently triggered from a select event, and there doesn't appear to be a onblur event for this function which I think is what I'm after. I'm new to JQuery and have already spent a day trying to sort it.
Code so far is:
$("#contact_name").autocomplete({
source: "get-caller-names.php",
minLength: 2,
select: function(event, ui) {
$('#contact_id').val(ui.item.id);
$('#contact_name').val(ui.item.name);
$('#contact_email').val(ui.item.email);
$('#contact_phone').val(ui.item.phone);
$('#contact_addr').val(ui.item.address);
}
});
All suggestions welcome, thanks.
Code in case others have the same issue...
// auto-suggest jqueryui
$("#contact_name").autocomplete({
source: "GetCallerNames.php",
minLength: 2,
select: function(event, ui) {
$('#contact_id').val(ui.item.id);
$('#contact_name').val(ui.item.name);
$('#contact_email').val(ui.item.email);
$('#contact_phone').val(ui.item.phone);
$('#contact_addr').val(ui.item.address);
},
change: function(event, ui) {
$.ajax({
type: 'GET',
url: 'GetCallerNames.php',
dataType: 'json',
data: {term:$(this).val()},
success: function(data) {
if (data!=null&&data!='') {
$('#contact_id').val(data[0].id);
$('#contact_email').val(data[0].email);
$('#contact_phone').val(data[0].phone);
$('#contact_addr').val(data[0].address);
}
}
});
}
});
Could you not add a new handler for change eg:
$( ".selector" ).autocomplete({
select: function(event, ui) { ... },
change: function(event, ui) { ... }
});

Categories