JQuery UI Autocomplete slow selecting an element - javascript

<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.

Related

MySQL data in JSON format to js function

I have DataTables table with data from one mysql table and after click on table row, I need to show data from another mysql table. I'm sending the data from both tables in JSON. I have this script (jsfiddle) and this is the php script to get the data from DB:
<?php
$tic = $_POST['name'];
$conn = mysqli_connect("192.168.2.11", "admin", "pass", "mydb");
$result = mysqli_query($conn, "SELECT TIME, DESC FROM table1, table2 WHERE table1.ACTION=ACT AND ID='" . $tic . "'");
// storing in array
$data = array();
while ($row = mysqli_fetch_assoc($result))
{
$data[] = $row;
}
echo json_encode($data);
// FOLLOWING CODE WORKS WITH THE CODE IN FIDDLE..
/*
echo json_encode( [
"html" => 'Details for <b>'.htmlentities($_POST['name']) . '<br><p>
] );
*/
$conn->close();
?>
This is my JSON I need to show in row details in table:
[
{"TIME":"2016-05-24 04:48:25","DESC":"Created"},
{"TIME":"2016-06-25 07:53:36","DESC":"Completion"}
]
I need to show the data from second ajax call in the format function and I need to style them to tables (not another datatable), because there will be more data in the future. I tried to modify format function and return rowData[0], but it returns data from 1st table, not the row details. Thanks
JSFIDDLE

How to return the elements of an array from my database into my php as Ajax links

Basically I have a database and I'm making a webpage with PHP.
I get a row of Elements from my database and put them into an array.
I need to display this array in my webpage, and the elements out of it have to be ajax links that display more information.
$sql = "SELECT * FROM categories";
$categories1 = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($categories1)) {
$id = $row["name"];
$echo "$id";
This is my array where i have a list of names and i print it there, i want my prints to be links.
Any help? I'm pretty desperate
Make the datatype of AJAX call as JSON in the javascript and return a json encoded string from php. Then in the success block of the AJAX call , parse it by JSON.parse()
$sql = "SELECT * FROM categories";
$categories1 = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($categories1)) {
$categoryDetails[] = $row;
}
echo json_encode( $categoryDetails );

How to auto-save and auto-update textarea

I'm currently attempting to create a test-website based on the "Secret Diary" project of a web developer course. I'm trying to create a page that saves all of the notes written into a textbox, and displays them when I log in again. Almost everything works - I can start a session and display the saved text when I log in, but the box is deleting the textbox's saved data when the page is loaded. I know that there are better ways of storing the info, I'm just looking for how to get this method to work. This should be all of the relevant code:
mainpage.php:
<?php include("updatediary.php"); ?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<form method="post">
<textarea class="form-control"><?php echo $diary; ?></textarea>
</form>
<script>
$("textarea").keyup(function() {
$.post("updatediary.php", function(){diaryInput:($("textarea").val());} );
});
</script>
updatediary.php:
<?php
include("connection.php");
$query = "SELECT content FROM users WHERE id='".$_SESSION['id']."' LIMIT 1";
$result = mysqli_query($dbCon,$query);
$row = mysqli_fetch_array($result);
$diary = $row['content'];
if ($_POST['diaryInput']!="") {
$updateQuery = "UPDATE `users` SET `content`='".mysqli_real_escape_string($dbCon, $_POST['diaryInput'])."' WHERE id='".$_SESSION['id']."' LIMIT 1";
if (mysqli_query($dbCon, $updateQuery)) {
echo "saved";
} else {
echo "not saved";
};
}
?>
connection.php:
$dbCon = mysqli_connect("localhost", "owenxwfg_admin", "(password)", "owenxwfg_users");
Any help would be awesome. I personally think that there's a problem with my $.post part.

javascript: verify if entered data exists in db and return data

I have a table:
DB
city
-------
cityID
cityname
store
I have then a form HTML:
<input type="text" class="store">
GOAL:
I would like javascript, after I enter the store, (if the entered value is already in the DB) displays an alert like:
"Store is already entered for the following cities: New York (ID#), Boston(ID#), Springfield(ID#)"
I've tried with a Json file:
<?php include ('connectionlink.php');
$word = $_GET['word'];
$search = "SELECT
store as value,
cityID,
cityname,
FROM city
WHERE store LIKE '%".$word."%'";
$result = mysqli_query($connection, $search);
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC))
{
$row['value']=htmlentities(stripslashes($row['value']));
$row['cityID']=$row['cityID'];
$row['cityname']=$row['cityname'];
$row_set[] = $row;
}
echo json_encode($row_set);
?>
And javascript
$(document).ready(function (){
$('.store').on('change', function(){
var storeValue = $('.store').val();
$.post('stores.php',{'word' : storeValue}, function(data) {
alert("Data: " + data);
});
});
});
I feel I'm almost there, because after typing the store I get an alert of Undefined index word error and then the alert displays all the data in my table with the Json format. It's like if it doesn't search just for my word, but just returns everything. Thanks for your help!
You are doing a post request, so read the parameter with $_POST
$word = $_POST['word']
Also make sure that you handle sql injection How can I prevent SQL injection in PHP?
<?php include ('connectionlink.php');
//as you are doing a post request...
$word = $_POST['word'];
$search = "SELECT
store as value,
cityID,
cityname,
FROM city
WHERE store LIKE '%".$word."%'";
$result = mysqli_query($connection, $search);
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC))
{
$row['value']=htmlentities(stripslashes($row['value']));
$row['cityID']=$row['cityID'];
$row['cityname']=$row['cityname'];
$row_set[] = $row;
}
echo json_encode($row_set);
?>

jQuery Autocomplete PHP Mysql posting different field

I am making use of jQuery's Autocomplete where I am populating my autocomplete dropdown with a php file called site.php. Site.php gets the values from a mysql table called site and which has 3 columns: id, code and site. I want my autocomplete to show only code and site and then store the corresponding id in my other table.
Everything works fine except that autocomplete is posting the code and the site selected but not the id. What do I need to change in order to send the id to my php POST and not code and site? Scripts as follows:
PHP file: site.php
<?php
$server = 'sql203.com';
$user = 'xxxxxxxxxxxx';
$password = 'xxxxxxx';
$database = 'b17';
$mysqli = new MySQLi($server,$user,$password,$database);
/* Connect to database and set charset to UTF-8 */
if($mysqli->connect_error) {
echo 'Database connection failed...' . 'Error: ' . $mysqli->connect_errno . ' ' . $mysqli->connect_error;
exit;
} else {
$mysqli->set_charset('utf8');
}
/* retrieve the search term that autocomplete sends */
$term = trim(strip_tags($_GET['term']));
$a_json = array();
$a_json_row = array();
if ($data = $mysqli->query("SELECT * FROM `b17_16413362_upupa`.`site` WHERE code LIKE '%$term%' OR site LIKE '%$term%' ORDER BY code , site")) {
while($row = mysqli_fetch_array($data)) {
$id = htmlentities(stripslashes($row['id']));
$code = htmlentities(stripslashes($row['code']));
$site = htmlentities(stripslashes($row['site']));
$a_json_row["id"] = $id;
$a_json_row["value"] = $code.' '.$site;
$a_json_row["label"] = $code.' '.$site;
array_push($a_json, $a_json_row);
}
}
// jQuery wants JSON data
echo json_encode($a_json);
flush();
$mysqli->close();
?>
Javascript:
<script type="text/javascript">
$(function() {
$("#sitex").autocomplete({
source: 'site.php',
minLength: 0
}).focus(function(){
$(this).autocomplete("search");
});
});
</script>
In your PHP, change
$a_json_row["value"] = $code.' '.$site;
to
$a_json_row["value"] = $id;
The 'value' property is the data that will be submitted by the form. The 'label' property is what will be displayed to the user.

Categories

Resources