jQuery autocomplete returns some null values - javascript

I'm using jQuery autocomplete with PHP source file that connects to MySQL and get the info to show as autocomplete on input field. Here's my code:
Index/Input
<script>
$(function() {
$("#search").autocomplete({
source: 'http://localhost/testes/autocomplete.php',
minLength: 3
});
});
</script>
<input type="text" id="search"/>
autocomplete PHP
$req = "SELECT DISTINCT name FROM faculty WHERE name LIKE '%".$_REQUEST['term']."%'";
$query = mysql_query($req);
while($row = mysql_fetch_array($query)){
$results[] = array('label' => $row['name']);
}
echo json_encode($results);
The problem is, it returns good values and other null values. But, in the last case, the values should not be null because they are in the database.
For example, in the database I have the entries:
ISCTE - Instituto Universitário
INDEG-ISCTE Business School
Searching by 'iscte' the autocomplete gives second one but the first one appear as null.
Thank you for you time,
Regards,
Hugo

That is because the encoding. Use this:
...
while($row = mysql_fetch_array($query)){
$results[] = array('label' => utf8_encode($row['name']));
}
...
Your database should set to UTF8, but by the way, this fix it.

Related

JQuery UI Autocomplete slow selecting an element

<script type="text/javascript">
$(function() {
$( "#customers" ).autocomplete({
source: 'search.php'
});
});
</script>
<div class="ui-widget"><input id="customers" name="Cno" placeholder="Customer Name"></div>
search.php
<?php include('header.php');
//get search term
$searchTerm = $_GET['term'];
//get matched data from skills table
$query = $db->query("SELECT * FROM customers WHERE Customer_Name LIKE '%".$searchTerm."%' ORDER BY Customer_Name ASC");
while ($row = $query->fetch_assoc()) {
$data[] = $row['Customer_Name'];
}
//return json data
echo json_encode($data);
?>
For Some arrays it was not working fine as I described in Jquery UI not working properly for some words And I added this code
$mysqli->set_charset('utf8mb4')
Then I faced issue in selecting element from dropdown, it takes too long to convert li class to ui-state-active, How to solve it?
Any help would be great!
In regards to your PHP, I would advise:
PHP
<?php
include('header.php');
//get search term
$searchTerm = $_GET['term'];
$data = array();
//get matched data from skills table
$query = $db->prepare("SELECT * FROM customers WHERE Customer_Name LIKE '%?%' ORDER BY Customer_Name ASC");
$query->bind_param('s', $searchTerm);
$query->execute();
$results = $query->get_result();
while ($row = $results->fetch_assoc()) {
$data[] = $row['Customer_Name'];
}
$query->close();
$db->close();
//return json data
header('Content-Type: application/json');
echo json_encode($data);
?>
This will help protect your scripts from SQL Injection.
In regards to your jQuery, I would advise:
JavaScript
$(function() {
$("#customers").autocomplete({
minLength: 3,
source: 'search.php'
});
});
If you enter 'sim', the autocomplete will send this to your PHP via GET. The response will be something like:
[
"Bart Simpson",
"Homer Simpson",
"Lisa Simpson",
"Maggie Simpson",
"Marge Simpson"
]
In your console, you should see this activity and can review the execution time. This will tell you how long the PHP is taking to provide a response to the request. This data should load in the autocomplete right away.
If you are seeing slowness, you will have to determine if it's in your PHP or JavaScript. That will determine where to look for issues.

Autocomplete form once the name is enter PHP

I found a couple of similar questions but nothing with the same "variables" so here we go:
I have a simple form where I enter a name and I need the rest of the form to be completed automatically (ID).
Fetching the data in the DB is not an issue, I'm able to return Json using PHP (Search.php):
//get search term
$searchTerm = $_GET['term'];
//get matched data from table
$query = $db->query("SELECT * FROM info_employer WHERE Prenom LIKE '%".$searchTerm."%' ORDER BY Prenom ASC");
while ($row = $query->fetch_assoc()) {
$data[] = array( Nom => $row['Prenom'] . ' ' . $row['Nom'], Num => $row['Num'] );
}
//return json data
echo json_encode($data);
This give me an array that look like this:
[{"Nom":"Andre Nadeau","Num":"104J"},{"Nom":"Andre Potvin","Num":"130J"},{"Nom":"Andre Thibodeau","Num":"91J"}]
Friends told me that I should use Jquery and Ajax to use this array to fill my form but I have 2 issue.
First If I return an Array instead of "just the name" my autocomplete form don't work anymore. It give me X numbers of blank space (depending the number of results).
And of course my biggest problem is that i'm not able to send the ID (Num) in the form
Javascript i'm using to autocomplete the name :
<script>
$(function() {
$( "#Nom" ).autocomplete({
source: 'Search.php',
})
})
</script>
You need to change the return object to make it match the spec here
$data[] = array( "label" => $row['Prenom'] . ' ' . $row['Nom'], "value" => $row['Num'] );
This should result in an array of objects with a 'label' and 'value' key. This will work with your autocomplete.

How can I have a PHP query select a certain table based on a drop down list selection?

I have a web program where the goal is plot data points for a certain Kiln that the user has selected. My problem is when a user wants to select a new Kiln, how can I update all the separate JSON pages to where the data is pulled from the new table they selected?
Here is my drop down list creater code.
<p class="navleft">
Kiln Number:<br>
<select name="kilns" id="kilns">
<?php
$sql = "SHOW TABLES FROM history";
$result = mysqli_query($con,$sql);
while($table = mysqli_fetch_array($result)) { // go through each row that was returned in $result
echo ("<option value='". $table[0] . "'>" . $table[0] . "</option>");
}
?>
</select>
</p>
And here is one of the php pages where I select all the data from a value in a table and turn it into a JSON file.
<?php
$con = mysqli_connect("localhost","KilnAdmin","KilnAdmin","history");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($con,"history") or die ("no database");
//Fetch Data
$query = "SELECT * FROM k1_history LIMIT 1000";
$result = mysqli_query($con,$query);
if ($result) {
$data = array();
while($row = mysqli_fetch_assoc($result)) {
//$data[] = $row;
$data[] = array(
"date" => $row[ 'Timestamp' ],
"value" => $row[ 'DryBulbFront' ]
);
}
echo json_encode($data);
}
else {
echo "Error";
}
?>
Where is says k1_history, how can I get that to be the selection from the user in the dropbox menu from the other page?
In this kind of scenario you have to strongly pay attention to avoid SQL injection. Use a whitelist approach as mentioned by Konstantinos Vytiniotis and check this out How can I prevent SQL injection in PHP?
If I understand correctly what you want, then what you need is Ajax.
You have to populate the select like you do and on each select, make an Ajax call to a .php where you will handle what the user has chosen. In your case this .php file is going to take the table name the user chose, run a query and return some results back to the html. For demonstration purposes, I'll explain with an example.
Let's say in your .html you have a select like this:
Select Value:
<select name="kilns" id="kilns">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
What defined in the value property of the option is what you are gonna pass to the .php file I mentioned. To do that, you use Ajax, so inside some script tags you have:
$('#kilns').on('change', function(e) {
var data = {'kilns': this.value};
$.ajax({
type: 'POST',
url: 'submit.php',
data: data,
dataType: 'json'
}).done(function(msg) {
alert(msg);
});
});
What this does is that every time a user selects something from the select, then this function is called, where the select's value (var data = {'kilns': this.value};) is being sent to a file named submit.php, via POST. The submit.php could look like this:
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
$kilns_error = 0;
if (isset($_POST['kilns']) && !empty($_POST['kilns'])) {
$kilns = $_POST['kilns'];
} else {
$kilns = null;
$kilns_error = 1;
}
if ($kilns_error != 1) {
echo json_encode($kilns);
}
}
What happens here is after we check we have indeed a POST REQUEST, we check whether the value is undefined or empty. After this simple check, we proceed to echo json_encode($kilns); where we return the value that we initially sent to the .php script, which in fact is the value the user selected.
In your case, what you have to do it to actually do some things in the .php script and not just return the value that you called it with. Also, make sure to pass the value you take through a whitelist to ensure that the user selects an actual table and is not trying to create problems for your database, cause it would be really easy to just change the value of what he is going to select before actually selecting it. Have a look at the prepared statements of the mysqli and PDO.

Automate search from database data into text field using php

I'm trying to automate my textfield of webform with auto search from database, where I have been trying it from many days. What I see is I get all the data which I typed but not with the data in the database. Can anyone help me out of this?
<script>
$(document).ready(function(){
$('input.module_nbr').module_nbr({
name: 'module_nbr',
remote:'search.php?key=%QUERY',
limit : 3
});
});
</script>
<?php
$key=$_GET['key'];
$array = array();
$dbc = mysqli_connect('','', '', '') OR die(mysqli_connect_error());
date_default_timezone_set("Asia/Calcutta");
$query=mysqli_query("select module_nbr from module_master where module_nbr LIKE '%{$key}%'");
while($row=mysqli_fetch_assoc($query));
{
$array[] = $row['module_nbr'];
}
echo json_encode($array);
?>
This will be a piece of code where I'm going to implement it in almost all fields of my form to reduce typing to the user.

Getting form data from both dependent drop down lists to php

I have a form on my page which includes 2 dependent drop down lists. When user selects value from 1st list, it populates the second list and user then selects value from 2nd list.
I want to submit form data to php page to insert into table in mysql, but when it submits, all data is passed EXCEPT value from 2nd list. Value from 1st list and other input fields are passed OK.
I've tried everything I know and I can't make this work. Any ideas how to implement this?
This is the form from index2.php (EDIT: simplified the form element):
<form name="part_add" method="post" action="../includes/insertpart.php" id="part_add">
<label for="parts">Choose part</label>
<select name="part_cat" id="part_cat">
<?php while($row = mysqli_fetch_array($query_parts)):?>
<option value="<?php echo $row['part_id'];?>">
<?php echo $row['part_name'];?>
</option>
<?php endwhile;?>
</select>
<br/>
<label>P/N</label>
<select name="pn_cat" id="pn_cat"></select>
<br/>
<input type="text" id="manufactured" name="manufactured" value="" placeholder="Manufactured" />
<input id="submit_data" type="submit" name="submit_data" value="Submit" />
</form>
And this is javascript:
$(document).ready(function() {
$("#part_cat").change(function() {
$(this).after('<div id="loader"><img src="img/loading.gif" alt="loading part number" /></div>');
$.get('../includes/loadpn.php?part_cat=' + $(this).val(), function(data) {
$("#pn_cat").html(data);
$('#loader').slideUp(200, function() {
$(this).remove();
});
});
});
});
And this is php to load 2nd list:
<?php
include('db_connect.php');
// connects to db
$con=mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$part_cat = $_GET['part_cat'];
$query = mysqli_query($con, "SELECT * FROM pn WHERE pn_categoryID = {$part_cat}");
while($row = mysqli_fetch_array($query)) {
echo "<option value='$row[part_id]'>$row[pn_name]</option>";
}
?>
I am getting $part_cat from 1st list to insertpart.php, but $pn_cat.
EDIT: this is insertpart.php (simplified and it just echos resuls)
<?php
//Start session
session_start();
//Include database connection details
require_once('../includes/db_details.php');
//DB connect
$con=mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
// find part name based on ID
$part_typeID = mysqli_real_escape_string($con, $_POST['part_cat']);
$part_name_result = mysqli_query($con, "SELECT part_name FROM parts WHERE part_id = $part_typeID");
$part_row = mysqli_fetch_array($part_name_result, MYSQL_NUM);
$part_type = $part_row[0];
echo"part_type='$part_type'";
//find pn value based on id
$pn_typeID = mysqli_real_escape_string($con, $_GET['pn_cat']);
$pn_name_result = mysqli_query($con, "SELECT pn_name FROM pn WHERE pn_id = $pn_typeID");
$pn_row = mysqli_fetch_array($pn_name_result, MYSQL_NUM);
$pn = $pn_row[0];
echo"pn='$pn'";
mysqli_close($con);
?>
It's still work in progress, so the code is ugly, and I know I'm mixing POST and GET that is being rectified. If I echo $pn_cat on this page there is no output, $part_type is OK.
Can you try swapping the $_GET in
$pn_typeID = mysqli_real_escape_string($con, $_GET['pn_cat']);
with $_POST?
$pn_typeID = mysqli_real_escape_string($con, $_POST['pn_cat']);
EDIT: based on asker's feedback and idea for a work-around
NOTE: This edit is based on what you suggested, even though I tested your original code and received satisfactory results (after I removed the PHP and MySQL from the code and replaced them with suitable alternatives).
The Work-Around
Here's the HTML for the hidden field:
<input type="hidden" id="test" name="test" value="" placeholder="test" />
Here's a simple Javascript function:
function setHiddenTextFieldValue(initiator, target){
$(initiator).change(function() {
$(target).val($(this).val());
});
}
You can call the above function within the function(data) { of your original code with something like:
setHiddenTextFieldValue('#pn_cat', '#test'); // note the hashes (#)
I also recommend you to hard-code the following HTML into your HTML and PHP files, right before the looping of the <option>s begin:
<option value="" disabled selected="selected">Select</option>
The above line could improve user experience, depending on how you want your code to work. Note however, that this is entirely optional.
Solved it! It was just a stupid typo, can't believe I've lost 2 days over this!
In loadpn.php instead of:
$row[part_id]
it should read:
$row[pn_id]
For some reason drop down worked, but offcourse value of pn_cat wasn't being set.
Also this works in setting 2 field values (which now I don't need but if somebody wants to know):
$(document).ready(function() {
$("#part_cat").change(function() {
$('#pn_hidden').val($(this).val());
});
$("#pn_cat").change(function() {
$('#pn_hidden2').val($(this).val());
});
});
Also changed js to post:
$(document).ready(function() {
$("#part_cat").change(function() {
$.post('../includes/loadpn.php', 'part_cat=' + $(this).val(), function(data) {
$("#pn_cat").html(data);
});
});
});
And thanks for the:
<option value="" disabled selected="selected">Select</option>
It really helps with user experience.

Categories

Resources