JQuery UI Autocomplete - hide result list when no matches - javascript

I have the following problem:
I have a working implementation of JQuery UI Autocomplete that gathers results from MYSQL Database and autotomatically fills some input fields based on user's choice.
What I am currently trying to get working is the situation when you type your search and there are no search results. Right now, the last suggested search items stay visible until you click away with mouse button. I would like to be able to hide it once there are no matching results. I have read a lot on this topic but nothing seemed to work for me. This is my Javascript part:
function AutoFill(x) {
var classname = "." + x;
$(document).on('keydown', classname, function(){
var id = this.id;
var splitid = id.split('_');
var index = splitid[1];
// Initialize jQuery UI autocomplete
$( '#'+id ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "get-details.php",
type: 'post',
dataType: "json",
data: {
search: request.term,request:1
},
success: function( data ) {
response(data);
}
});
},
select: function (event, ui) {
$(this).val(ui.item.label); // display the selected text
var userid = ui.item.value; // selected value
// AJAX
$.ajax({
url: 'get-details.php',
type: 'post',
data: {userid:userid,request:2},
dataType: 'json',
success:function(response){
var len = response.length;
if(len > 0){
var id = response[0]['id'];
var name = response[0]['name'];
var number = response[0]['number'];
// Set value to textboxes
document.getElementById('clientname').value = name;
document.getElementById('clientnumber').value = number;
}
}
});
return false;
}
});
});
}
And this is my PHP file, that searches through the Database:
<?php
include('includes/dbconnection.php');
$request = $_POST['request']; // request
// Get username list
if($request == 1){
$search = $_POST['search'];
$query = "SELECT * FROM tblclients WHERE FullName like'%".$search."%' OR MobileNumber like'%".$search."%'";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result)){
$response[] = array("value"=>$row['ID'],"label"=>$row['FullName'].' | '.$row['MobileNumber']);
}
// encoding array to json format
echo json_encode($response);
exit;
}
// Get details
if($request == 2){
$userid = $_POST['userid'];
$sql = "SELECT * FROM tblclients WHERE ID=".$userid;
$result = mysqli_query($con,$sql);
$users_arr = array();
while( $row = mysqli_fetch_array($result) ){
$userid = $row['ID'];
$fullname = $row['FullName'];
$number = $row['MobileNumber'];
$users_arr[] = array("id" => $userid, "name" => $fullname,"number" => $number);
}
// encoding array to json format
echo json_encode($users_arr);
exit;
}
I don't know what I'm doing wrong...

Related

How to get the value of title image and content in ajax php

How to display the data title, image and content?
Here's the code:
view.php
$id = $_REQUEST['edit_literature_id'];
$literature = $_REQUEST['literatureID'];
$module = $_REQUEST['edit_moduleId'];
if (isset($id)) {
$dataArr = array();
$responseArr = array();
$sql = "SELECT * FROM $literature WHERE `id`='".$id."'";
if ($result = mysqli_query($conn, $sql)) {
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$data['title'] = $row['title'];
$data['name'] = 'data:image/jpeg;base64,' . base64_encode($row['name']);
$data['content'] = $row['content'];
array_push($dataArr, $data);
}
echo json_encode($dataArr);
}
mysqli_free_result($result);
} else {
echo "No Record";
}
}
index.php
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
rowId = $(this).attr('data-id');
moduleData = $(this).attr('data-module');
literatureData = $(this).attr('data-literature');
$('#edit_id').val(rowId);
$('#edit_module').val(moduleData);
$('#edit_literature').val(literatureData);
$('#edit_imageId').val(rowId);
$('#update').val('update');
$.ajax({
type: 'POST',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (data) {
alert(data)
}
});
});
});
What I'm trying to do is to get the title, image and content.
How to get the value of title, image and content?
How to call the "title", "name" and "content" from the php?
console.log('DATA: ' + data);
No need to use while loop for result. Also remove extra $dataArr and $responseArr
Update your code to:
in view.php
$id = $_REQUEST['edit_literature_id'];
$literature = $_REQUEST['literatureID'];
$module = $_REQUEST['edit_moduleId'];
if (isset($id)) {
$sql = "SELECT * FROM $literature WHERE `id`='".$id."'";
if ($result = mysqli_query($conn, $sql)) {
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_array($result);
$data['title'] = $row['title'];
$data['name'] = 'data:image/jpeg;base64,' . base64_encode($row['name']);
$data['content'] = $row['content'];
echo json_encode($data); exit;
}
mysqli_free_result($result);
}
}
$data['error'] = "No Record";
echo json_encode($data); exit;
Index.php
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
rowId = $(this).attr('data-id');
moduleData = $(this).attr('data-module');
literatureData = $(this).attr('data-literature');
$('#edit_id').val(rowId);
$('#edit_module').val(moduleData);
$('#edit_literature').val(literatureData);
$('#edit_imageId').val(rowId);
$('#update').val('update');
$.ajax({
type: 'POST',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (data) {
var response = jQuery.parseJSON(data);
var title = response.title;
var name = response.name;
var content = response.content;
alert(title);
alert(name);
alert(content);
}
});
});
});
After taking data from jQuery side, you can set value in html side using id or class attribute in jQuery.
How your ajax receiving .php file should look:
$validLiteratureIds = ['yourTable1', 'yourTable2'];
if (!isset($_GET['edit_literature_id'], $_GET['literatureID']) || !in_array($_GET['literatureID'], $validLiteratureIds)) {
$response = ['error' => 'Missing/Invalid Data Submitted'];
} else {
$conn = new mysqli('localhost', 'root', '', 'dbname');
$sql = "SELECT title, name, content
FROM `{$_GET['literatureID']}`
WHERE `id` = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $_GET['edit_literature_id']);
$stmt->execute();
$stmt->bind_result($title, $name, $content);
if (!$stmt->fetch()) {
$response = ['error' => 'No Record'];
} else {
$response = [
'title'=> $title,
'name' => 'data:image/jpeg;base64,' . base64_encode($name),
'content' => $content
];
}
}
echo json_encode($response);
Important practices:
Validate the user input so that only qualifying submissions have the privilege of accessing your database.
Write the failure outcomes before success outcomes consistently throughout your project, this will make your scripts easier to read/follow.
Always use prepared statements and bind user-supplied data to placeholders into your query for stability/security.
The tablename cannot be bound like the id value; it must be written directly into your sql string -- this is why it is critical that you validate the value against a whitelist array of literature ids.
There is no need to declare new variables to receive the $_GET values; just access the values directly from the superglobal array.
I am going to assume that your id is a primary/unique key in your table(s), so you don't need to loop over your result set. Attempt to fetch one row -- it will either contain data or the result set was empty.
Call json_encode() only once and at the end of your script.
It is not worth clearing any results or closing a prepared statement or a connection, because those tasks are automatically done when the script execution is finished anyhow -- avoid the script bloat.
As for your jquery script:
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (response) {
if (response.hasOwnProperty('error')) {
console.log(response.error);
} else {
console.log(response.title, response.name, response.content);
}
}
});
});
});
I've trim away all of the irrelevant lines
changed POST to GET -- because you are merely reading data from the database, not writing
parseJSON() is not necessary -- response is a ready-to-use object.
I am checking for an error property in the response object so that the appropriate data is accessed.
Both scripts above are untested (and completely written from my phone). If I have made any typos, please leave me a comment and I'll fix it up.

How to parse large data via POST query

I am creating a webpage having Excel like features to create a Plan.For this i need to fill an initial form and click on submit button , then submit the form using ajax to a server side PHP script which inserts these records to a Mysql table.
But the issue is i can only transfer 1-2 records of table using the POST Query as there is a limit to it.What should i do in this case?Is there any other way of doing it without expanding the POST query limit?
My Front end code(.js)
</script>
buttons.save.addEventListener('click', function() {
var r1 = hot.countRows() - hot.countEmptyRows() - 1;
var c1 = hot.countCols()- 1 ;
var data = String(hot.getData(0,0,r1,c1));
data = data.replace(/,/g,'');
document.getElementById('all_data').value= JSON.stringify(hot.getData(0,0,r1,c1));
document.getElementById('colheaders').value=JSON.stringify(hot.getColHeader());
console.log(hot.getInstance());
var testplan_name = document.getElementById('feature_name').value;
var product = document.getElementById('product').value;
var release = document.getElementById('release').value;
var pv_engg = document.getElementById('pv_engg').value;
var pe_engg = document.getElementById('pe_engg').value;
var rd_engg = document.getElementById('rd_engg').value;
var tp_completion = document.getElementById('tp_completion').value;
var at_completion = document.getElementById('at_completion').value;
var all_headers = document.getElementById('colheaders').value;
var all_data = document.getElementById('all_data').value;
var maker = document.getElementById('maker').innerHTML;
var datastring = 'testplan_name='+testplan_name+'&product='+product+'&release='+release+'&pv_engg='+pv_engg+'&pe_engg='+pe
_engg+'&rd_engg='+rd_engg+'&tp_completion='+tp_completion+'&at_completion='+at_completion+'&headers='+all_headers+'&all_data='
+all_data+'&maker='+maker;
if(testplan_name=="" || pv_engg =='' || pe_engg== '' || rd_engg== '' || product=='' || release=='') {
else if(data=="") {
alert("For creating a testplan , you need to fill this table.");
}
else {
alert(datastring);
$.ajax({
url :"save_create_pro.php",
type :"POST",
data : datastring,
cache : false,
success :function(result) {
console.log(result);
alert(result);
alert("Form Submitted successfully");
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
}
return false;
});
});
</script>
My Backend php code:
<?php
$dbh=mysql_connect('noiwebfarmo','abc','xyz');
if(! $dbh ) {
die('Could not connect: ' . mysql_error());
}
$database=mysql_select_db('testmohit');
$testplan_name=$_POST['testplan_name'];
$product=$_POST['product'];
$release=$_POST['release'];
$pv_engg=$_POST['pe_engg'];
$pe_engg=$_POST['pe_engg'];
$rd_engg=$_POST['rd_engg'];
$tp_completion=$_POST['tp_completion'];
$at_completion=$_POST['at_completion'];
$maker=$_POST['maker'];
$headers=stripslashes($_POST['headers']);
$all_data = stripslashes($_POST['all_data']);# to remove \ before " that occur when parsed through ajax
$headers=preg_replace('/\["/','',$headers);
$headers=preg_replace('/"\]/','',$headers);
$headers=split('","',$headers);
for($j=0;$j<count($headers);$j++) {
$headers[$j]= str_replace(' ','_',strtolower("$headers[$j]"));
}
$date=date('Y-m-d');
$all_data=preg_replace('/\[\["/','',$all_data);
$all_data=preg_replace('/"\]]/','',$all_data);
$rows_data=split('"\],\["',$all_data);
or($i=0;$i<count($rows_data);$i++) {
$data[$i] = split('","',$rows_data[$i]);
}
$result = array();
foreach($data as $key => $val){
$temp = array();
foreach($val as $k => $v){
$temp[$headers[$k]] = $v;
}
$result[] = $temp;
}
#print $all_data;
print count($result);
print_r($result);
for($i=0;$i < count($result);$i++) {
$temp = $result[$i];
$query = "INSERT INTO testplans (testplan_name,product,pro_release,percent_tpcompletion,percent_atcompletion,pv_engineer,rnd_engg,pe_engg,tc_name,cell_name,customer_name,flops,title,status,mfix_ccr,test_scenerio,expected_results,ccr_no,ccr_status,remarks,create_date,maker) VALUES ('$testplan_name','$product','$release','$tp_completion','$at_completion','$pv_engg','$rd_engg','$pe_engg','$temp[testcase_name]','$temp[cell_name]','$temp[customer]','$temp[flops]','$temp[title]','$temp[status]','$temp[mfix_ccr]','$temp[scenerio_brief_description]','$temp[expected_results]','$temp[ccr_no]','$temp[ccr_status]','$temp[remarks]','$date','$maker')";
mysql_select_db('testmohit');
$enter=mysql_query($query,$dbh);
if(! $enter) {
die('Could not enter data: ' . mysql_error());
}
}
# echo "$query Entered data successfully";
mysql_close($dbh);
?>
Please provide a solution to insert large no. of rows of handson table without expanding the size of query string .What can be the solution of this problem.
Thanks in advance.

Jquery getting more than one variable

I have a small script that runs a php file in the background and gets a variable every 3 seconds and put it in a div
script in document with div
<script>
$(document).ready(function() {
setInterval(function () {
$('#statmoney').load('safe.php');
}, 3000);
});
</script>
PHP FILE (safe.php)
$sql = "SELECT * FROM users WHERE id='".$_SESSION['user_id']."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
$money = htmlspecialchars($row->money);
echo $money;
If i need to add another variable i would need to make a new document is there a easy way to go about it?
UPDATE
menu.php
<script>
$(document).ready(function() {
setInterval(function () {
var fields = ['money', 'ore', 'energy']; // array of needed fields
$.ajax({
type: "POST",
url: "menusafe.php",
data: {'fields': fields},
dataType: 'json',
success: function(response) {
// assuming that we already have divs for respective fields
fields.forEach(function(v){
console.log(response)
$("#" + v).html(response[v]);
});
}
});
}, 3000);
});
</script>
<div class="menustats"><img src="graphics/logos/moneylogo.png" class="menustatimage"><div class="menustattext" id='money'></div></div>
<div class="menustats"><img src="graphics/logos/energylogo.png" class="menustatimage"><div class="menustattext" id="energy"></div></div>
<div class="menustats"><img src="graphics/logos/orelogo.png" class="menustatimage"><div class="menustattext" id='ore'></div></div>
PHP(menusafe.php)
<?php
if ( isset($_POST['fields']) && !empty($_POST['fields']) && is_array($_POST['fields']) ){
$fields = $_POST['fields'];
$fields = (count($fields) > 1)? implode(',', $fields) : $fields;
$sql = "SELECT $fields FROM users WHERE id='".$_SESSION['user_id']."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
$result = [];
foreach($fields as $field){
$result[$field] = $row->{$field};
}
echo json_encode($result);
}
?>
Let's imagine that we want to retrieve three fields from users table : firstname, age and money. In such case it would be better to use $.post or $.ajax method:
js part:
<script>
$(document).ready(function() {
setInterval(function () {
var fields = ['firstname', 'age', 'money']; // array of needed fields
$.ajax({
type: "POST",
url: "safe.php",
data: {'fields': fields},
dataType: 'json',
success: function(response) {
// assuming that we already have divs for respective fields
fields.forEach(function(v){
$("#" + v).html(response[v]);
});
}
});
}, 3000);
});
</script>
php part: (safe.php)
if ( isset($_POST['fields']) && !empty($_POST['fields']) && is_array($_POST['fields']) ){
$fields = $_POST['fields'];
$fields = (count($fields) > 1)? implode(',', $fields) : $fields;
$sql = "SELECT $fields FROM users WHERE id='".$_SESSION['user_id']."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
$result = [];
foreach($fields as $field){
$result[$field] = $row->{$field};
}
echo json_encode($result);
}

how to retrieve echo data from php to jquery 1 by 1

I have a JQuery on click that sends a php query to MySql and then I want to send the data back 1 by 1 on JQuery.
But I only know how to send back results from php to JQuery as a whole.
my current JQuery:
$(function() {
$(".img_thumb_holder").on("click", function() {
$.ajax({
type: "POST",
url: "CMS/PHP/retrieveAuthorDetails.php",
success: function(data) {
alert(data);
}
});
});
});
my current php:
<?php
include 'dbAuthen.php';
$sql = "SELECT * FROM users WHERE Name = 'james'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
echo $row['UserID'];;
echo $row['EmailAddr'];
}
?>
the outputs are both UserID and EmailAddr, I don't know how to just display either the UserID or EmailAddr out only
I tried alert(data[0]), but it only displayed one letter of the result.. Any ideas on how to do this?
UPDATE: After sean's help i have the current updated code
Jquery:
$(function() {
$(".img_thumb_holder").on("click", function() {
$.ajax({
type: "POST",
dataType: "json",
url: "CMS/PHP/retrieveAuthorDetails.php",
success: function(data) {
$.each(data, function() {
var userid = data.userid;
var useremail = data.email;
// i think there something wrong with this as it will keep repeating storing the userid and email for each data.. can someone verify?
});
}
});
});
});
PHP
<?php
include 'dbAuthen.php';
$sql = "SELECT * FROM users WHERE Name = 'honwenhonwen'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
$arr = array(
"userid" => "HonWen",
"email" => "honwen#hotmail.com"
);
}
echo json_encode($arr);
?>
In your php, save the results to an array -
<?php
include 'dbAuthen.php';
$array = array(); // create a blank array
$sql = "SELECT * FROM users WHERE Name = 'james'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
// add each result to the array
$array[] = array('UserID'=> $row['UserID'], 'EmailAddr'=> $row['EmailAddr']);
}
echo json_encode($array); // json_encode() the array
?>
Then in your js/ajax you can loop through each value
$(function() {
$(".img_thumb_holder").on("click", function() {
$.ajax({
type: "POST",
url: "CMS/PHP/retrieveAuthorDetails.php",
success: function(data) {
// loop through each returned value
$.each(data, function(){
//alert each result, this is just an example as alert() for each result is not a great idea
alert("UserID:"+ this.UserID + " EmailAddr:" + this.EmailAddr);
});
}
});
});
});
jquery
$(function() {
$(".img_thumb_holder").on("click", function() {
$.ajax({
type: "POST",
dataType: "json",
url: "CMS/PHP/retrieveAuthorDetails.php",
success: function(data) {
$.each(data, function() {
var userid = data.userid;
var useremail = data.email;
// i think there something wrong with this as it will keep repeating storing the userid and email for each data.. can someone verify?
});
}
});
});
});
php
<?php
include 'dbAuthen.php';
$sql = "SELECT * FROM users WHERE Name = 'honwenhonwen'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
$arr = array(
"userid" => "HonWen",
"email" => "honwen#hotmail.com"
);
}
echo json_encode($arr);
?>

Upvote button on website with JavaScript, Php, AJAX, MySql not working. What am I doing wrong?

I'm trying to create upvote/downvote buttons on a list of articles that I get from a MySql database. The buttons work in the sense that you press on the button and it gets the id of the article. However I can't get the id from article page to the php voting page. When I press the button the database doesn't register the vote. What am I doing wrong?
<script type="text/javascript">
$(function() {
$(".vote").click(function()
{
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if(name=='up')
{
alert('you upvoted on '+ dataString);
$(this).fadeIn(200);
$.ajax({
type: "POST",
url: "weblectureupvote.php",
data: dataString,
cache: false,
});
}
else
{
alert('you downvoted on '+ dataString);
$(this).fadeIn(200);
$.ajax({
type: "POST",
url: "weblectureupvote.php",
data: dataString,
cache: false,
});
}
return false;
});
});
</script>
This is the php file:
<?php
$pid = $_POST['id'];
try {
$db = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['dbname'], $config['db']['username'], $config['db']['password']);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result=mysql_query("SELECT * FROM database WHERE pid = '$pid' ") or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
// temp user array
$lecturelist = array();
$lecturelist["pid"] = $row["pid"];
$lecturelist["upvote"] = $row["upvote"];
$lecturelist["downvote"] = $row["downvote"];
$lecturelist["vote"] = $row["vote"];
}
$upvote= $row["upvote"];
$downvote = $row["downvote"];
$vote = $row["vote"];
$upvote = $upvote + 1;
$query = $db->prepare('UPDATE database SET upvote = :upvote WHERE pid = :pid');
$query->execute(array(
':upvote' => $upvote,
':pid' => $pid
));
$query = $db->prepare('UPDATE database SET vote=:vote WHERE pid = :pid');
$query->execute(array(
':vote' => $vote,
':pid' => $pid
));
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
data: {id: id}
this will get to your php file a "id" variable ( this is the first id ) and with some value ( from the second id )
now
$pid = $_POST['id'];
this should work, as you weren't sending "much" to the server

Categories