jQuery autocomplete field not autocompleting when getting data from remote database - javascript

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.

Related

PHP dynamic dropdown menu Get Value by ID [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Here's the background info for my question: I'm selecting data from an SQL table, which has the columns "ID (osm_id)", "Names" and "Coordinates (way)" with around 300 entries each. I got a dropdown menu to work displaying all the possible names of pubs (they are in column "Names").
Now I wanna get the coordinates of a selected pub and have those displayed on the page.
Here's my code so far:
<?php
...
$query = "SELECT osm_id, name, ST_asText(ST_transform(way,4326)) FROM planet_osm_polygon WHERE amenity LIKE 'pub' ORDER BY name ASC;";
$result = pg_query($query) or die("Query error: " . pg_last_error());
?>
<select id="pub_select" name="pub_select" size="1">
<option value="">--- Select a Pub ---</option>
<?php
$options='';
while($line = pg_fetch_row($result))
{
$pub_id = $line[0];
$pub_names = $line[1];
$way_coords = $line[2];
$options.="<option value='" . $pub_names . "'>$pub_names</option>";
echo $options;
}
pg_free_result($result);
pg_close($dbconn);
?>
</select>
<input type="submit" name="submit" value="Get building coordinates" />
My tutor suggested that I could use:
<select id="pub_select" name="pub_select" size="1" onchange="getMoreInfo()">
and call a function getMoreInfo() in order to do the detailed query (Pub ID -> Pub coordinates) and use pub_select = document.getElementById('pub_select'); for the ID in Javascript/Ajax-Call of my php code and basically filter with the ID to get the coordinates. But I dont know how to do that :/
EDIT:
So, basically my question is: I have a database table, I choose a pub from a drop down menu. How do I get further information from the same table, like the coordinates from the corresponding column.
You could modify the HTML you generate slightly to include a dataset attribute for each option in the select menu.
The Javascript event handler getmoreinfo will read that dataset attribute and use it in part of an ajax request to some backend php script that will fetch more results from the db.
<select id='pub_select' name='pub_select' size='1' onchange='getmoreinfo(e)'>
<option selected disabled hidden>--- Select a Pub ---
<?php
while( $line = pg_fetch_row( $result ) ){
printf(
'<option value="%s" data-latlng="%s">%s',
$line[0],
$line[2],
$line[1]
);
}
?>
</select>
A simple version of what you might use in the getmoreinfo function to send an ajax request using the fetch api.
<script>
function getmoreinfo(e){
/* choose the correct path for backend script */
let baseurl='/path/to/backend/script.php';
/* create the request payload */
let args={
'latlng':e.target.dataset.latlng,
'id':e.target.value
};
/* generate the full url & querystring for the GET request */
let url=baseurl + '?' + Object.keys(args).map(key=>{
return [ encodeURIComponent(key), encodeURIComponent(args[key]) ].join('=')
}).join('&');
/* issue the ajax request */
fetch( url )
.then( r=>r.text() )
.then( text=>{
/* process the final response here */
alert( text )
})
}
</script>
A pseudo-code version of the backend script that the ajax request is sent to... this is pseudo code and untested.
<?php
# /path/to/backend/script.php
if( $_SERVER['REQUEST_METHOD']=='GET' && isset(
$_GET['latlng'],
$_GET['id']
)){
$latlng=$_GET['latlng'];
$id=$_GET['id'];
$sql='select from sometable where id=? and latlng=?';
$stmt=$dbo->prepare($sql);
#... etc
}
?>
To clarify a few things. You can pass the selected value from the select element i.e.
<select id="pub_select" name="pub_select" size="1" onchange="getMoreInfo(this.value)">
In the Javascript code you would have
<script>
function getMoreInfo( value ) {
...
}
If you do not have to use AJAX to get the results you can plug this info into the option value i.e.
while($line = pg_fetch_row($result)) {
$data = implode( "|", $line );
$pub_names = $line[1];
echo "<option value='" . $data . "'>$pub_names</option>";
}
This will but the | delimiter between each piece of data.
In your JavaScript function you would extra it by:
<script>
function getMoreInfo( value ) {
var data = value.split("|");
}
To sent the information out to the web page you need an element where you can display the data. Use a div i.e.
<div id='results'></div>
Now put your data into the div i.e.
<script>
function getMoreInfo( value ) {
var data = value.split("|");
document.getElementById('results').innerHTML = "Name : "+data[1]+"<br>Co-ords : "+data[2];
}
If you have to use AJAX then things get a lot more complicated.

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

PHP array as JSON response for jQuery autocomplete

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.

External PHP data not passing through AJAX

I'm working on creating a simple online booking system using PHP and AJAX.
The current layout is:
Each booking grabs a preset list of items then users can add additional items that they need.
To do this I have set up an AJAX button that calls a new drop down list each time its clicked. (This means a page could have 1 additional item or even 20, depending on how many they need.)
Once the additional items have been selected, they can then submit the form and will be guided to a confirmation page that is meant to list what they have chosen.
The issue:
None of the data is being carried through from any of the drop down lists that get added.
My AJAX script and php code on page 1 is:
<script>
function changeIt()
{
$.ajax({
type: "POST",
url: "details.php"
}).done(function( result ) {
$("#msg1").append( "" +result);
});
}
</script>
<form name ="addequip" id="addequip" action="confirmbooking.php" method="post">
<input type='button' value="Add Item" onClick="changeIt()"/>
<div id="msg1"></div>
<input type='submit' value='submit'/>
details.php:
<?php
require_once("dbconn.php");
$sql = "SELECT REFERENCE, DESCRIPTION FROM descEquip";
$result = mysql_query($sql,$conn);
?>
<select name="equip">
<?php while ($row = mysql_fetch_array($result)) { ?>
<option value="<?php echo $row["REFERENCE"];?>"><?php echo $row["DESCRIPTION"];?></option><?php } ?>
</select>
And lastly my confirmation page is:
<?php $item = $_POST['equip']; ?>
<?php echo $item ?>
I'm not too sure if i need to add something to the AJAX script in order for this to work as intended or if something needs to be changed in the details.php? (I'm very new to AJAX)
I have viewed a previous question 'passing form data to mySQL through AJAX' and I couldn't make it work for me.
Lastly, for additional lists (when more than 1 item is required) do I need to have a feature that states each equip list have a different name? likename="equip<?php echo $i ?> where $i = 1++;
Any tips or examples would be appreciated,
thanks.
Never assume all will work as you want it - check if sth goes wrong in your code:
var jqxhr = $.ajax(
{
type: 'GET',
async: false,
url: 'details.php',
success: function(data, textStatus /* always 'success' */, jqXHR)
{
// ok if we are here it means that communication between browser and apache was successful
alert( 'on_ajax_success data=[' + data + '] status=[' + textStatus + ']' );
$("#msg1").innerHTML( result );
}
,
error: function(jqXHR, textStatus, errorThrown)
{
alert( 'ERROR: [operation failed]' );
}
});
Moreover - use Firefox with Firebug installed so that you can see your ajax queries/responces.

Categories