Good afternoon, I’m trying jQuery ajax autocomplete for the first time and it seems to be working great but I have found my self in a bit of problem, you see I have a sql table name
Clients: with the following columns, id_client , clinent_name , id_user,
Basically each table is assigned to a user . and that’s where my problem comes
in index.php I have the following code :
<script type="text/javascript">
$(function() {
$("#name").autocomplete({
source: "/cliente.php",
minLength: 1,
select: function(event, ui) {
event.preventDefault();
$('#client_name').val(ui.item.client_name);
$('#id_client').val(ui.item.id_cliente); })});
</script>
Which sends the value of the input with the name =’name’ to cliente.php
if (isset($_GET['term'])){
include 'include/conexion.php';
$return_arr = array();
if ($con)
{
$fetch = mysqli_query($con,"SELECT * FROM cliente where name like '%" .
mysqli_real_escape_string($con,($_GET['term'])) . "%' LIMIT 0 ,50");
while ($row = mysqli_fetch_array($fetch)) {
$id_cliente=$row['id_cliente'];
$row_array['value'] = $row['id_client']." | ".$row['cliente_name']; a
rray_push($return_arr,$row_array); }} mysqli_close($con); echo json_encode($return_arr);}
But the problem is I’m trying to send another value to cliente.php which is id_user so the user could only look up clients assign to them.
In PHP. we have to change the row array.
$row_array['value'] = $row['id_client']." | ".$row['cliente_name']; =>
$row_array[] = $row['id_client']." | ".$row['cliente_name'];
In js, we have to parse the return value. Label and value are the same in autocomplete success callback.
select: function(event, ui) {
event.preventDefault();
var values= ui.item.value.split("|");
if (values.length > 1) {
$('#client_name').val(values[1]);
$('#id_client').val(values[0]);
}
}
Related
Ok where to start, I will try and explain as much as I can.
I am using wordpress with contact form 7 and I am trying to populate 3 dropdown items on the contact form, I found some code that I was able to use with no problem but the problem with this was that it was getting the information from a excel file, the file is now to big and will not run on my website anymore so I would like to get the information from my database now.
I have made a table in my database "vehicle_information" with 3 columns "vehicle_type", "vehicle_make", vehicle_model"
I have code in my functions.php and code in my footer to be able to use the cf7 shortcodes.
Code from funtions.php
function ajax_cf7_populate_values() {
//MySQLi information
$db_host = '***';
$db_username = '***';
$db_password = '***';
$vehicles_makes_models = array();
//connect to mysqli database (Host/Username/Password)
$connection = mysqli_connect($db_host, $db_username, $db_password) or die('Error ' . mysqli_error());
//select MySQLi dabatase table
$vehicles_makes_models = mysqli_select_db($connection, 'vehicle_information') or die('Error ' . mysqli_error());
$sql = mysqli_query($connection, 'SELECT * FROM vehicle_type');
while($row = mysqli_fetch_array($sql)) {
$vehicles_makes_models[$row[0]][$row[1]][] = $row[2]; }
}
// setup the initial array that will be returned to the the client side script as a JSON object.
$return_array = array(
'vehicles' => array_keys($vehicles_makes_models),
'makes' => array(),
'models' => array(),
'current_vehicle' => false,
'current_make' => false
);
// collect the posted values from the submitted form
$vehicle = key_exists('vehicle', $_POST) ? $_POST['vehicle'] : false;
$make = key_exists('make', $_POST) ? $_POST['make'] : false;
$model = key_exists('model', $_POST) ? $_POST['model'] : false;
// populate the $return_array with the necessary values
if ($vehicle) {
$return_array['current_vehicle'] = $vehicle;
$return_array['makes'] = array_keys($vehicles_makes_models[$vehicle]);
if ($make) {
$return_array['current_make'] = $make;
$return_array['models'] = $vehicles_makes_models[$vehicle][$make];
if ($model) {
$return_array['current_model'] = $model;
}
}
}
// encode the $return_array as a JSON object and echo it
echo json_encode($return_array);
wp_die();
// These action hooks are needed to tell WordPress that the cf7_populate_values() function needs to be called
// if a script is POSTing the action : 'cf7_populate_values'
add_action( 'wp_ajax_cf7_populate_values', 'ajax_cf7_populate_values' );
add_action( 'wp_ajax_nopriv_cf7_populate_values', 'ajax_cf7_populate_values' );
Code from my footer
<script>
(function($) {
// create references to the 3 dropdown fields for later use.
var $vehicles_dd = $('[name="vehicles"]');
var $makes_dd = $('[name="makes"]');
var $models_dd = $('[name="models"]');
// run the populate_fields function, and additionally run it every time a value changes
populate_fields();
$('select').change(function() {
populate_fields();
});
function populate_fields() {
var data = {
// action needs to match the action hook part after wp_ajax_nopriv_ and wp_ajax_ in the server side script.
'action' : 'cf7_populate_values',
// pass all the currently selected values to the server side script.
'vehicle' : $vehicles_dd.val(),
'make' : $makes_dd.val(),
'model' : $models_dd.val()
};
// call the server side script, and on completion, update all dropdown lists with the received values.
$.post('<?php echo admin_url( 'admin-ajax.php' ) ?>', data, function(response) {
all_values = response;
$vehicles_dd.html('').append($('<option>').text(' -- choose vehicle -- '));
$makes_dd.html('').append($('<option>').text(' -- choose make -- '));
$models_dd.html('').append($('<option>').text(' -- choose model -- '));
$.each(all_values.vehicles, function() {
$option = $("<option>").text(this).val(this);
if (all_values.current_vehicle == this) {
$option.attr('selected','selected');
}
$vehicles_dd.append($option);
});
$.each(all_values.makes, function() {
$option = $("<option>").text(this).val(this);
if (all_values.current_make == this) {
$option.attr('selected','selected');
}
$makes_dd.append($option);
});
$.each(all_values.models, function() {
$option = $("<option>").text(this).val(this);
if (all_values.current_model == this) {
$option.attr('selected','selected');
}
$models_dd.append($option);
});
},'json');
}
})( jQuery );
The problem is I am still learning and this is the first time I have had to use this funtion.
and I am getting an error on my website
Warning: array_keys() expects parameter 1 to be array, null given in /customers/4/0/0/motobid.co.uk/httpd.www/wp-content/themes/storevilla-child/functions.php on line 38 {"vehicles":null,"makes":[],"models":[],"current_vehicle":false,"current_make":false}
any help would be very greatful.
Just like to say code was supplied by BDMW.
Where you use the method array_keys(), instead of:
$return_array['makes'] = array_keys($vehicles_makes_models[$vehicle]);
Try this:
$return_array['makes'] = ! empty($vehicles_makes_models[$vehicle]) ? array_keys($vehicles_makes_models[$vehicle]) : [];
From what I've read, the array_keys() has been an issue depending on php versions. Hope this helps!
So I've been working on this code for awhile now and I've done a lot of debugging but can't figure this out. What I want to do is: if a checkbox is checked send a request to run a query on the mySQL database FROM items WHERE .class(of the checkbox) '<' this.value(of the checkbox again) then get the filtered results and then use my javascript to format it:
index.php:
<form>
<label><input type="checkbox" class="calories "name="calories" value="300">Less than 300</label><br>
<label><input type="checkbox" class="calories" name="calories" value="500">Less than 500</label><br>
</form>
<script>
$("input.calories:checkbox").on("change",function(){
if(this.checked){
var column = $(this).attr('class'); //The class determines which column of the table is called
var value = $(this).attr('value'); //Takes the numeric value from the selected box
console.log(column);
//$.post('showItems.php', {type: column});
//$.post('showItems.php', {value: value});
//Can we call the php code above to run a query using variables column and value?
//make a php function above and call it
// function below will run showItemss.php?c=column?v=value
$.ajax({
type: "POST",
url: "showItems.php" ,
data: { c: column,
v: value},
error: function(){console.log("error")},
success: function(data) {
console.log("success");
console.log(test);
console.log(filteredList);
</script>
Here is the PHP file showItems.php I'm calling (the relevant part):
//This array holds items from database.
$itemList = array();
//Connect and Select
$con = makeConnection($dbhost, $dbuser, $dbpass, $dbname);
//Get the value and type from the javascript below
//If the type is null display the whole table
$c = $_POST['c'];
//echo $c;
//$v = mysqli_real_escape_string($con,$v);
//$type = $_POST['value'];
if($c==null){
$query = "SELECT * FROM items";
}
else{
$v = $_POST['v'];
$query = "SELECT * FROM items WHERE ".$c."< ".$v."";
}
$result = mysqli_query($con, $query);
//Collect data from all items
while($row = $result->fetch_assoc())
{
$tempItem = new Item($row['itemID'], $row['itemName'], $row['price'], $row['description'], $row['calories'], $row['protein'], $row['choles'], $row['sodi'], $row['picLink']);
$itemList[] = $tempItem;
}
echo json_encode($query);
?>
<script>
var test = <?php echo json_encode($query); ?>;
var filteredList = <?php echo json_encode($itemList); ?>;
</script>
So I want this code to be run every time I click a checkbox in my Index.php file so I can get the updated filtered items, $itemList, but I cannot figure out how to do this. Something I've done to test this is store my php values as javascript variables, Include showItems.php then console.log the variables from ShowItems.php in Index.php, and the query isn't being updated upon click which makes sense I guess. In the AJAX success function 'data' contains the entire HTML source with an updated query, but I can't figure out how use only the specific code I need in the success function. Any ideas at all would be helpful.
Try doing this:
Go from on("change",...) to on("click",...)
Also try using instead of this.checked, $(this).prop("checked") which will return you true or false depending on wether the checkbox is checked or not.
You might want to change either your selector or your checkbox classes because both are the same, and can give you undesired functionality in order to get your values when you click on a checkbox, since the selector finds you both checkboxes.
Hope this ideas can get you closer where you want to be.
Cheers
I have a search form where I want to display suggestions via jQuery autocomplete when 3 characters are typed. The suggestions are drawn from a mySQL DB.
What happens: jQuery does successfully transmit the typed chars to the PHP file, where they successfully get embedded in an mySQL query.
When I open the PHP file separately with an assumed search term, f.e. like this: /soplogsearch.php?term=xyz it works perfectly and I see the aimed at result of echo json_encode($return_arr);
but back on the HTML search form file autocomplete doesn't suggest a thing. I have no errors in the console. I tried to echo the json_encode elsewhere on the HTML file and its output was Null.
I have made a fiddle for the (very simple) Javascript/jQuery and HTML set up: https://jsfiddle.net/9bf6s07f/1/
the relevant PHP code looks like this:
if (isset($_GET['term']))
{
$term = $_GET['term'];
$termwild = "%$term%";
$return_arr = array();
$service = mysql_query("SELECT DISTINCT service FROM master WHERE service LIKE \"" . $termwild . "\"");
while ($data = mysql_fetch_array($service))
{
$return_arr[] = $data[0];
}
json_encode($return_arr);
echo json_encode($return_arr);
}
EDIT: For quicker access I'm including the HTML and jQuery parts of the code here instead of link you to the fiddle https://jsfiddle.net/9bf6s07f
<body>
<label>Service:</label>
<input type='text' name='' value='' class='auto'>
</body>
and jQuery:
$(document).ready(function() {
$(function() {
$(".auto").autocomplete({
source: "soplogsave.php",
minLength: 3
});
});
});
Does someone know what I'm doing wrong? I tested autocomplete separately with a set of javascript variables and it worked fine.
EDIT 2: Because all of the comments seem to imply my PHP is wrong and I'd have an error in the console, I made a screenshot from the network tab of the console: http://i.imgur.com/i6nAQ98.png
This is how I have achieved it in my code:
PHP
$param = $_GET["term"];
$stk_adddep = "
SELECT * FROM stocktake_products WHERE stocktake_id = '{$stocktake_id}' AND is_deli = 0 AND (product_code LIKE '%{$param}%' OR product_name LIKE '%{$param}%'); ";
//FB::info($stk_adddep);
//echo $stk_adddep;
//die();
$result = db::c()->query($stk_adddep);
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$row_array['itemCode'] = $row['product_code'];
$row_array['itemDesc'] = $row['product_name'];
//$row_array['itemPrice'] = $row['unit_cost_price'];
array_push( $return_arr, $row_array );
}
/* Free connection resources. */
//mysql_close($conn);
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
And then javascript
$(document).ready(function(){
// Use the .autocomplete() method to compile the list based on input from user
var url10 = '<?php echo Navigation::gUrl('/users/admin/stocktake_details_cocktails.php', array('stocktake_id' => $stocktake_id, 'action' => 'find_products'));?>';
$('#itemCode').autocomplete({
source: url10,
minLength: 1,
select: function(event, ui) {
var $itemrow = $(this).closest('tr');
// Populate the input fields from the returned values
$itemrow.find('#itemCode').val(ui.item.itemCode);
$itemrow.find('#itemDesc').val(ui.item.itemDesc);
//$itemrow.find('#itemPrice').val(ui.item.itemPrice);
// Give focus to the next input field to recieve input from user
$('#itemQty').focus();
return false;
}
// Format the list menu output of the autocomplete
}).data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.itemCode + " - " + item.itemDesc + "</a>" )
.appendTo( ul );
};
See if you can maybe apply this to your code?
The answer was posted in the comments by user #n00dl3.
I am trying to autofill input text 1 and fill a 2nd input based on the select on field 1. My sql works great.
In the html form - ids are formfieldname1 and formfieldname2
The autocomplete works on field 1, but wont carry the 2nd value over to the 2nd text field
At the bottom of my form field I have this
<script>
// JQUERY AUTOCOMPLETION
$(function() {
$( "#formfieldname1" ).autocomplete({
source: "vessels6.php",
minLength: 1, //search after one characters
});
});
</script>
and on the vessels6.php page this...
<?php
// Basic oci_connect() database connection
connection here
$return_arr = array();
$term = strtoupper(trim(strip_tags($_GET['term'])));//retrieve the search term that autocomplete sends
$sql = oci_parse($conn,"SELECT FIELD1, FIELD2, FROM TABLE1 WHERE MAX_DATE_CANCELED >= TRUNC(sysdate) and (FIELD1 LIKE '%$term%' OR FIELD2 LIKE '%$term%') ");
oci_execute($sql, OCI_DEFAULT);
while ($row = oci_fetch_array($sql, OCI_ASSOC+OCI_RETURN_NULLS)) {
$row_array["label"] = $row['FIELD1'] . ' - ' . $row['FIELD2'];
$row_array["value"] = $row['FIELD1'];
$row_array['FIELD2'] = $row['FIELD2'];
array_push( $return_arr, $row_array );
}
oci_close($conn);
// Truncate, encode and return the results
$return_arr = array_slice($return_arr, 0, 8);
echo json_encode($return_arr),"\n";
?>
I am using jQuery UI Autocomplete and I choose a selection in 1 text inout and want another input field to populate...
I want to limit search to Names using jqueryUi's auto-complete so that results returned are only Names and don't include other array values like fax and stuff.
Here's my php.
<?php
require_once 'db_conx.php';
$req = "SELECT * "
."FROM profiles "
."WHERE name LIKE '%".mysql_real_escape_string($_REQUEST['term']) ."%' ";
$query = mysql_query($req);
while($row = mysql_fetch_array($query))
{
$return = array ('label' => $row['name'],
'founder' => $row['founder'],
'fax' => $row['fax']
);
}
echo json_encode($return);
?>
Javascript
$(function() {
$( "#SearchInput").autocomplete({
source: '../Search/BP_Search.php',
minLength: 2,
autoFocus: false,
select: function(event, ui) {
$('#ProName' ).html(ui.item.name);
$('#ProFax' ).html(ui.item.fax);
$('#ProFounder' ).html(ui.item.founder);
}
});
Thanks.
When the source is an array of objects - [ { label: "Choice1", value: "value1" }, ... ], only the label (or value if the label is not provided) is searched/displayed in the suggestion menu http://api.jqueryui.com/autocomplete/#option-source. So you can have fax, founder, and other key/value sets in your returned array and they will not be searched/displayed.
An alternative is that you only get the names in your php script, and then on select you do an ajax request to get all other data.
note: you are using ui.item.name -
$('#ProName' ).html(ui.item.name);
but name in not in your array, so it should be label
$('#ProName' ).html(ui.item.label);