PHP array as JSON response for jQuery autocomplete - javascript

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.

Related

how to send a secound value in autocomplete ajax

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]);
}
}

jquery autocomplete input field nothing happens

I want to implement one autocomplete input field but when I start to insert some text nothing happens, for one sec the "busy circle" shows up and that is all.
Here is my code:
html>
<div class="products-inv"><?php echo $product_name ?></div>
<input type="text" id="product_name" name="product_name" />
the first div is test for displaying the php variable value what shows up well
jquery>
jQuery( function() {
function log( message ) {
jQuery( "<div>" ).text( message ).prependTo( "#log" );
jQuery( "#log" ).scrollTop( 0 );
}
jQuery( "#product_name" ).autocomplete({
source: "../route/to/search.php",
minLength: 2,
select: function( event, ui ) {
log( "Selected: " + ui.item.value + " aka " + ui.item.id );
}
});
} );
and the search.php file content>
$query = 'database data';
$db->setQuery( $query );
$product_name = $db->loadResult();
the error console is empty.
thanks in advice
your server side code does not return the data expected by the plugin.
From the documentations of the jQuery autocomplete plugin about the source option
When a string is used, the Autocomplete plugin expects that string to
point to a URL resource that will return JSON data
your search.php script must return the items you want to suggest to the user (show up in the autocomplete list )
that is an example:
/*term is a parameter generated by the plugin and contains
the string the user has typed in the input*/
$_GET['term'] = isset($_GET['term']) ? $_GET['term'] : null;
//manage your own query depending on your database and preferred way for db interactions
//$query = "select product_name from product where product_name like ?";
//$term = "%{$_GET['term']}%";
//$stmt = $mysqli->prepare($query);
//$stmt->bind_param("s", $term);
//$stmt->execute();
//$result = $stmt->get_result();
$autocompleteList = [];
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$autocompleteList[] = $row['product_name'];
}
die(json_encode($autocompleteList));

Jquery Autocomplete and MySQL ID Value

hoping someone can help me out with something.
I've got a piece of code which allows the Jquery Autocomplete. What I'm wanting to do is to use the ID(primary key) from my MySQL table and then use that to POST on to another screen.
How would I go about getting the ID into a hidden value from the Jquery code?
Here are my snippets.
Jquery
<script>
$(function() {
$( "#skills" ).autocomplete({
source: 'JQUERYTEST.php'
});
});
</script>
Html
<div class="ui-widget">
<label for="shop">Shopname: </label>
<input id="shop">
</div>
Php/MySQL
<?php
//database configuration
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'aurora';
//connect with the database
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
//get search term
$searchTerm = $_GET['term'];
//get matched data from skills table
$query = $db->query("SELECT * FROM shops WHERE shopname LIKE '%".$searchTerm."%'");
while ($row = $query->fetch_assoc()) {
$data[] = $row['shopname'] . ' - '. $row['streetaddress'] . ' - ' . $row['postcode'];
}
//return json data
echo json_encode($data);
?>
Thanks!
Firstly, you will have to use an Ajax call to get the data from the server. So, change your autocomplete function and add an ajax call to receive a response. Then you will have to loop the JSON array in jquery. I have created the id as the whole string with shopname, streetaddress and postcode. Currently, your code doesn't inserts the ID parameter from the database. You can create an id depending on your needs. Then dynamically I have created the HTML and then placed it inside the <div class="ui-widget">
<script>
$( function() {
$( "#skills" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "search.php",
dataType: "jsonp",
data: {
term: request.term
},
success: function( data ) {
var html = "";
$.each(data, function(i, item) {
var arr = item.split('-');
html += "<label for='shop'>Shopname:"+arr[0]+" </label><input id='"+item+"' type='hidden'><br>";
});​
$('.ui-widget').html(html);
}
});
}
});
});
</script>
Try this out. I hope this helps you.

Javascript: search autocomplete - fetch results from mysql database?

I am trying to achieve a search bar on my website that shows a list of suggestive search results as a user types them in.
So if someone starts to type in Hew
and the value Hewden exists in my database then this will show up in the suggestive search results drop down list
I have the following html form setup on my page search.php:
search.php
<form action="include/search_source.php" method="post" name="searchForm">
<input type="text" name="search" class="Search_bar_box" id="search" autocomplete="off">
</form>
<script>
jQuery(document).ready(function($){
$('#search').autocomplete({source:'include/search_source.php', minLength:2, select: function (event, ui) {
window.location = 'search_results.php?search=' + ui.item.value;
}});
$('#searchForm').on("submit", function (event) {
event.preventDefault();
alert($('#search').val());
});
});
</script>
In search_source.php i have the following code which runs a mysql query which is suppose to lookup my values from the database:
search_source.php:
<?php
include 'config.php';
$rs = mysql_query('select * from supplier_stats where company_name like "'. mysql_real_escape_string($_REQUEST['term']) .'%" OR supplier_number like "'. mysql_real_escape_string($_REQUEST['term']) .'%" OR descrip like "'. mysql_real_escape_string($_REQUEST['term']) .'%" order by company_name asc limit 0,5');
// loop through each zipcode returned and format the response for jQuery
$data = array();
if ( $rs && mysql_num_rows($rs) )
{
while( $row = mysql_fetch_array($rs, MYSQL_ASSOC) )
{
$data[] = array(
'label' => $row['company_name'] .' - '. $row['supplier_number'] .' - '. $row['descrip'] ,
'value' => $row['company_name']
);
}
}
// jQuery wants JSON data
echo json_encode($data);
flush();
?>
I am then including search.php in my page dashboard.php like so:
<?php include 'search.php'; ?>
For some reason this code works on my local host server but doesn't work on my main server. can someone please show me what i am doing wrong? or perhaps show me a better way of doing this? Thanks in advance

jQuery autocomplete field not autocompleting when getting data from remote database

I'm trying to get a jQuery autocomplete field to work with data from a remote DB, and I'm having no luck. Here's what I've attempted so far:
1.I have all of the necessary links to the source code in my header.
2.I have the following jQuery script written:
<script>
$(function() {
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}
$( "#projNo0" ).autocomplete({ //projNo0 is the name of the autocomplete field
source: "projects.php",
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
});
</script>
3.This is the PHP backend that's supposed to populate the autocomplete field projNo0 (the DB connection is handled elsewhere in the same file):
$return_arr = array();
if ($con2) //If the DB connection is successful
{
//Get the user's input from projNo0
$ac_term = "%".$_GET['term']."%";
$query = $con2->prepare("SELECT CodeID FROM CodeTable WHERE
CodeID LIKE :term");
$data = array('term'=>$ac_term);
$query->execute($data);
while ($row = $query->fetch(PDO::FETCH_ASSOC))
{
$row_array['CodeID'] = $row['CodeID'];
array_push($return_arr,$row_array);
//echo $row['CodeID']; //line used for testing
//echo '<br />'; //line used for testing
}
}
4.And here is the HTML for my autocomplete field. It's part of an array:
<p class="ui-widget">
<input type="text" name="projNo[]" id="projNo0" value="<? php echo $projNo[0]; ?>" />
</p>
I can confirm that there's no problem connecting to the remote DB. I'm able to echo out the array of values the SELECT statement returns. The jQuery script only works, however, when I hardcode an array of values into it. (Replace source "projects.php" with ["Bob","Carol","Ted","Alice"], for example.) When I right-click on the field and inspect it, the network activity shows that projects.php is being called and that it's accepting my input, appending it as a GET variable. The status of that activity is "OK". But I get no drop-down list of autofill suggestions.
Where is the break between my application and the database? I'm assuming that's where the problem is, since the script works with hardcoded values.
Replace this
while ($row = $query->fetch(PDO::FETCH_ASSOC))
{
$row_array['CodeID'] = $row['CodeID'];
array_push($return_arr,$row_array);
//echo $row['CodeID']; //line used for testing
//echo '<br />'; //line used for testing
}
With this
echo json_encode(array_values($query->fetchAll(PDO::FETCH_COLUMN, 0)));
The point is - autocomplete expexts JSON-encoded string as an answer, and you return nothing from your script. Using array_reduce to get the resulting array is just my preference.

Categories