Javascript: search autocomplete - fetch results from mysql database? - javascript

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

Related

PHP doesn't output error from mysql query for non-existent rows for autocomplete

I have a form that currently is able to auto complete base on user input, it queries the MySQL database and successfully lists all possible matches in the table and give suggestions. Now I want to handle rows that do not exist. I am having trouble to get my PHP file to echo the error. Here is what I have so far:
I'm guessing in my auto search function in my javascript in main.php I need to return the error message to the page?
search.php
<?php
//database configuration
$host = 'user';
$username = 'user';
$password = 'pwd';
$name = 'name';
//connect with the database
$dbConnection = new mysqli($host,$username,$password,$name);
if(isset($_GET['term'])){
//get search term
$searchTerm = '%'.$_GET['term'].'%';
//get matched data from skills table
if($query = $dbConnection->prepare("SELECT * FROM nametbl WHERE name LIKE ? ORDER BY name ASC")) {
$query->bind_param("s", $searchTerm);
$query->execute();
$result = $query->get_result();
//$row_cnt = $result->num_rows;
//echo $row_cnt;
if($result -> num_rows){
while ($row = $result->fetch_assoc()) {
$data[] = $row['name'];
}
//return json data
echo json_encode($data);
mysqli_close($dbConnection);
}
else { echo '<pre>' . "there are no rows." . '</pre>'; }
}
else {
echo '<pre>' . "something went wrong when trying to connect to the database." . '</pre>';
}
}
?>
main.php
<div id="gatewayInput">
<form method="post">
<input type="text" id="name" name="name" placeholder="Name..."><br><br>
<?php
include("search.php");
?>
</div>
...
...
...
<script src ="../../../jqueryDir/jquery-3.2.1.min.js"></script>
<script src ="../../../jqueryDir/jquery-ui.min.js"></script>
<script type="text/javascript">
//auto search function
$(function() {
$( "#name" ).autocomplete({
source: 'search.php'
});
});
1.your method type is post in the form
in main.php
and in the search.php, you have used "if(isset($_GET['term'])){"
this needs to be fixed I guess. either both needs to be POST or GET.
Again you are using include method which the whole code in search.php will be made in-line and treated as a one file main.php. so you need not use GET or Post method.
How does get and Post methods work is
3.1) you have a html or PHP which submits the data from browser(main.php), and this request is being served by an action class(search.php)
example :- in main.php
3.2) now in search.php you can use something like if(isset($_POST['term'])){
You can use num_rows (e.g. if ($result -> num_rows)) to see if the query returned anything.

Getting a PHP input form arguments with JavaScript's autocomplete

I am trying to build PHP input forms with autocompletion.
When a user types something into the form, a database should be searched and all the words matching what the user typed should be returned. I am trying to use Autocomplete from jQuery.
I've tried to use a dedicated PHP page as a source for the autocomplete function. Since there are many different inputs, I would like to write generic code to search the database. I am trying to send this request:
SELECT DISTINCT ("name of the input form")
FROM MyDB
WHERE "name of the input form" LIKE '%value typed by user%'
The name of each input is the name of a column in the DB.
How do I get the input form's name to use it?
thank you for the tips, I am quite new here.
So here is the code in the php page with the form. Actualy, it is already a function :
<!doctype html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$( ".query" ).autocomplete({
source: "function_lister_autocomp.php",
});
} );
</script>
</head>
<body>
<?php /*function that print the form*/
function field($attribut, $fieldName) {
$val='';
if(isset($_POST[$attribut])){$val=$_POST[$attribut];} //if the users entered a value, reminds it
echo'<tr><td>'.$fieldName.'</td>';
echo'<div class="ui-widget">';
echo '<td><input class="query" type="text" name='.$attribut.' value='.$val.'>';}
echo'</div>';
echo'</td></tr>';
}
?>
</body>
So the source of the data would be the page "function_lister_autocomp.php". I would like to transmit both the value entered by the user AND THE NAME OF THE FORM to this page. Here is the code :
<?php
$val = $_REQUEST["term"] //value entered by user
$name = $_REQUEST["name"] //name of the form
//request sent to the base
try {
$bd = new PDO('mysql:host=X','X','X');
}
catch(Exception $e) {die ('Erreur : '. $e -> getMessage());}
$answer = $bd->query("SELECT DISTINCT(".$name.") FROM SEQUENCAGES WHERE ".$name." LIKE '%".$val."%'");
// fetch data
while($data = $answer->fetch()) {
$return_arr[] = $data[0];
}
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
?>
How to actually GET THE VARIABLE $NAME is my big problem...
If someone knows how to do, thank you very much :) !

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.

Need help to get auto suggest to display (in list-form) the fetched/matched data from database

I am having problem solving the following:
I have a form with one search field (with autosuggest).
In this field I would like to be able to type a name or mobile.nr.
Based on what I type I get suggestions, so typing letters or numbers returns: name and mobile based on matches in the database.
If no match is found a "create customer" button shall appear.
If a match is found a "create work-card" button shall appear.
In my code below I am getting all the data from my customer table, but I can not figure out how to make it show in list form with one row per result including the persons name and mobile in the autosuggest ex:
suggestion 1: name and mobile
suggestion 2: name and mobile
suggestion 3: name and mobile
etc…..
My autosuggest script:
<script type="text/javascript">
$(document).ready(function() {
//autocomplete
$(".input_name_or_mobil").autocomplete({
source: "search.php",
minLength: 1
});
});
</script>
The script searches in my search.php file:
<?php
if ( !isset($_REQUEST['term']) )
exit;
$connect = mysql_connect('localhost', 'root', '') or die( mysql_error() );
mysql_select_db('workcard');
$results = mysql_query('SELECT name AS shout FROM customer WHERE name LIKE "'. mysql_real_escape_string($_REQUEST['term']) .'%" UNION SELECT mobil FROM customer WHERE mobil LIKE "'. mysql_real_escape_string($_REQUEST['term']) .'%" ORDER BY 1 LIMIT 10', $connect);
$data = array();
if ( $results && mysql_num_rows($results) )
{
while( $row = mysql_fetch_array($results, MYSQL_ASSOC) )
{
$data[] = array(
'label' => $row['shout'],
'value' => $row['shout']
);
}
}
echo json_encode($data);
flush();
?>
If i understood you question:
You are using UNION, so the records will be after each others.
Try this:
$results = mysql_query("SELECT name, mobile FROM customer WHERE name LIKE '" . mysql_real_escape_string($_REQUEST['term']) . "%' OR mobil LIKE '" . mysql_real_escape_string($_REQUEST['term']) . "%' ORDER BY 1 LIMIT 10", $connect);
$data = array();
if ($results && mysql_num_rows($results)) {
while ($row = mysql_fetch_array($results, MYSQL_ASSOC)) {
$data[] = array(
'label' => $row['name'] . " " . $row['mobile'],
'value' => $row['name'] . " " . $row['mobile']
);
}
}
In this code, you will be get back the name and mobile fields form the table, and all the records wher name OR mobil is similar than the term.
Use mysqli_ function because mysql_ functions are deprecated.

copy value of jquery UI auto-complete in select function to a textfield?

I created this javascript wherein it will create a row of textfield for multiple insertion purposes.. My problem is I'd like to add an auto complete wherein it will query the data inserted on the text field from the database and fill its remaining data record on other textfield. It seems I having a problem in putting the data on the textfield since its id is incremented.
here's my code:
HTML
<form name="zxc" method="POST">
<div id="sit" align="center"><label><input type="text" id="set" name="set" placeholder="Set number of rows..."></label>
<button type="button" id="cret" class="btn btn-warning btn-sm" onClick="createinput();hide();autoComp();">Add rows</button></div>
<br>
Javascript
function autoComp(){
$(function(){
var id2=0;
var num = parseInt(document.forms["zxc"]["set"].value);
if(!num) return;
for(var count=1;count<=num;count++, id2++){
$("#unit"+id2).autocomplete({
source:'search2.php',
minLength:1,
select:function(evt, ui) {
this.form.description+id2.value = ui.item.description;
this.form.unit_value+id2.value = ui.item.unitValue;
}
});
}
});
}
PHP
include '../core/database/config.php';
$term= $_GET["term"];
$rs= mysql_query("SELECT unit,description,unitValue FROM csr_inventory where unit like '%".$term."%' order by unit");
$data = array();
if ( $rs && mysql_num_rows($rs) ) {
while( $row = mysql_fetch_array($rs) )
{
$data[] = array(
'value' => $row['unit'] ,
'description' => $row['description'] ,
'unitValue' => $row['unitValue']
);
}
}
echo json_encode($data);
flush();
please help me solving this problem... :(

Categories