I'm having some troubles with my code, I want it to execute the php file whenever I enter something but it isn't working
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
function getStates(value) {
$.post("search.php", {name:value},function(data)
$("#results").html(data);
});
}
</script>
</head>
<input type="text" onkeyup="getStates(this.value)"/>
<br>
<div id="results"></div>
<body>
</body>
</html>
php
<?php
mysqli_connect("localhost", "#", "#") or die(mysqli_connect_errno());
mysql_select_db("#") or die(mysql_error());
$search = $_POST["name"];
$players = mysql_query("SELECT firstname FROM players WHERE firstname LIKE '%search%'");
while($player = mysql_fetch_array($players)) {
echo "<div>" . $players["firstname"] . "</div>";
}
?>
From what I can see,you should change this
'%search%'
to
'%{$search}%'
in
$players = mysql_query("SELECT firstname FROM players WHERE firstname LIKE '%search%'");
EDIT
#user3187651 Assuming you've done everything right on the server side.
Change your javascript to:
function getStates(value) {
$.post("search.php", {name:value},function(data){
$("#results").html(data);
}
);
}
This should get rid of the error in the client side.
You are missing {. Just do:
function xyx(name) {
$.post("search.php", { name: value }, function(data) {
$("#results").html(data);
});
}
There's something that is missing in your code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> //ur getting the jquery via online
<script>
$(document).ready(function(){
$("#textBoxId").change(function() //triggers when you change the value in your textbox
{
var value = $(this).val(); //gets the value of your textbox
$.post("search.php", {id:value},function(data)
$("#results").append(data);
});
}
});
</script>
</head>
<body>
<input type="text" id="textBoxId"/>
<br>
<div id="results"></div>
</body>
</html>
And in your php:
<?php
mysqli_connect("localhost", "#", "#") or die(mysqli_connect_errno());
mysql_select_db("#") or die(mysql_error());
$search = $_POST['id'];
$returnData = "";
$players = mysql_query("SELECT firstname FROM players WHERE firstname LIKE '%search%'");
while($player = mysql_fetch_array($players)) {
$returnData .= "<div>" . $players["firstname"] . "</div>";
}
echo $returnData;
For more secure and creative back-end code, you can use this.
<?php
$host = 'localhost';
$user = 'root';
$password = '';
$database = 'dev_testing';
$mysqli = new mysqli($host, $user, $password, $database);
$username = $_GET['username'];
$username = trim(htmlspecialchars($username));
$like = '%' . strtolower($username) . '%';
$statement = $mysqli -> prepare('
SELECT name, picture, description
FROM users
WHERE lower(name) LIKE ?
ORDER BY INSTR(title, ?), title
LIMIT 20'
);
if (
$statement &&
$statement -> bind_param('ss', $like, $username) &&
$statement -> execute() &&
$statement -> store_result() &&
$statement -> bind_result($name, $picture, $description)
) {
$array = [];
while ($statement -> fetch()) {
$array[] = [
'name' => $name,
'picture' => $picture,
'description' => $description
];
}
echo json_encode($array);
exit();
}
Advantages of the code
Prevents SQL Injection
Orders results from the best match
Sends a JSON response (JSON is light-weight)
Full Tutorial:
Live Search with AJAX, PHP, and MYSQL
Related
I am trying to build some ZingCharts with weatherdata from a homemade weatherstation. Currently I am using Google Charts, but would rather use Zing as it seems a whole lot easier to work with. Except, I can't get it to pull data from my Database. Below I have the demo example from ZingChart git, all I did was change the variables concerning my sql server. But it just shows an empty page. Looking at the page source after loading reveals that it doesn't fill the arrays with any data at all.
<!DOCTYPE html>
<html>
<head>
<title>MySQL Demo</title>
<script type="text/javascript" src="http://cdn.zingchart.com/zingchart.min.js"></script>
</head>
<body>
<script>
<?php
$host = "localhost";
$port = 3306;
$usernm = "pi";
$passwd = "";
$dbname = "weatherDB";
$query = "SELECT timestamp, temperature from bme680 ORDER BY id ASC";
$time = [];
$temperature = [];
$mysqli = new mysqli($host, $usernm, $passwd, $dbname, $port);
if($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ')' . $mysqli->connect_error);
}
if ($result = $mysqli->query($query)) {
while( $row = $result->fetch_array(MYSQLI_NUM)){
array_push($time, $row[0]);
array_push($temperature, $row[1]);
}
$result->close();
}
?>
var dateValues = [<?php echo join($time, ',') ?>];
var seriesValues = [<?php echo join($temperature, ',') ?>];
<?php
$mysqli->close();
?>
</script>
<script>
window.onload=function(){
zingchart.render({
id:"myChart",
width:"100%",
height:400,
data:{
"type":"line",
"title":{"text":"Data Pulled from MySQL Database"},
"scale-x":{
"values": dateValues,
"transform":{
"type":"date",
"item":{
"visible":false
}
}
},
"plot":{"line-width":1},
"series":[ {"values":seriesValues}]
}
});
};
</script>
<h1>Database Data</h1>
<div id="myChart"></div>
</body>
</html>
I am trying to use a code that was flagged as working and I am not getting any results, it's just empty. Notes: The MySQL does return results if run alone, so it's not an sql thing. Any suggestions?
HTML:
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<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>
</head>
<body>
Name: <input id="hint" />
<script type="text/javascript">
$("#hint").autocomplete({
source: function (request, response) {
$.ajax({
url: "getMedicineNames.php",
dataType: "jsonp",
data: {
name: request
},
success: function (data) {
response(data);
}
});
},
minLength: 3
});
</script>
</body>
PHP:
require 'connect.inc.php';
$mysql = mysqli_connect("$db_host", "$db_username", "$db_pass", "$db_name");
$name = $_POST['name'];
if ($name != "") {
$sql = "SELECT MedicineName FROM medicinetypes WHERE MedicineNAme LIKE '%$name%'";
echo json_encode(mysqli_fetch_all(mysqli_query($mysql, $sql), MYSQLI_ASSOC));
}
Please add dataType: "json", & type : "GET".
If not working please add your screenshot of JSON response.
Bilal Ahmed answer is correct.
Aditinoally this is a bit incorrect:
$name = $_POST['name']; // Maybe cause a PHP Warning
You can solve this creating a unset value:
$name = isset($_POST['name']) ? $_POST['name'] : "";
/* "" can be NULL, FALSE, 0 or any value */
In PHP7 you can make this:
$name = $_POST['name'] ?? "";
/* "" can be NULL, FALSE, 0 or any value */
Alright I found a better answer, but the main problem was my php code where I left the array as an assoc which is wrong.
JS:
$(function () {
$("#hint").autocomplete({
source: 'getMedicineNames.php'
});
});
PHP:
$mysql = mysqli_connect("$db_host", "$db_username", "$db_pass", "$db_name");
$name = $_GET['term'];
$sql = "SELECT MedicineName FROM medicinetypes WHERE MedicineNAme LIKE '%$name%'";
$res = mysqli_query($mysql, $sql);
$res = mysqli_fetch_all($res, MYSQLI_ASSOC);
foreach($res as $row){
$data[]=$row['MedicineName'];
}
echo json_encode($data);
I am trying to make an autocomplete php interacts with database, but find more than 10 online resource, cannot make it work with my database.
Here is the index.php code:
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/themes/base/minified/jquery-ui.min.css" type="text/css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.1/jquery-ui.min.js"></script>
<script>
$(function() {
//autocomplete
$("#model").autocomplete({
source: "search.php",
minLength: 1
});
});
</script>
</head>
<body>
<form action='' method='post'>
<p><label>Model:</label><input type='text' id="model" name='model' class='model'/></p>
</body>
</html>
Here is the search.php:
<?php
define('DB_SERVER', 'localhost');
define('DB_USER', 'root');
define('DB_PASSWORD', '123456');
define('DB_NAME', 'inventory');
if (isset($_GET['term'])){
$return_arr = array();
$conn = new mysqli(DB_SERVER,DB_USER,DB_PASSWORD,DB_NAME);
$stmt = $conn->stmt_init();
$term = '%'.$_GET['term'].'%';
$stmt = $conn->prepare("SELECT name from items WHERE name like ?");
$stmt->bind_param("s", $term);
$stmt->execute();
$stmt->bind_result($models);
while( $row = $models){
$return_arr[] = $row['name'];
}
echo json_encode($return_arr);
}
?>
And some tutorial use fetch_array() that is not working on my script why? It only work with regular loop such as while loop to store array from database and then use foreach to echo every rows. I am using $mysqli->fetch_array().
Which part is wrong?
You should do this:
Replace the "bind_result" line with this (just for convenience):
$stmt->bind_result($name);
Then replace your while loop with this:
while ($stmt->fetch()) {
$return_arr[] = $name;
}
And it should work.
Basically for each column in your query you add a variable in the bind_result statement and use those when iterating over the results;
use below codes and go through the url#,
http://www.codexworld.com/autocomplete-textbox-using-jquery-php-mysql/
//get matched data from skills table
$query = $db->query("SELECT * FROM skills WHERE skill LIKE '%".$searchTerm."%' ORDER BY skill ASC");
while ($row = $query->fetch_assoc()) {
$data[] = $row['skill'];
}
//return json data
echo json_encode($data);
I'm trying to do the following:
from a html page, pushing a button will call a php script which query a db and echoes json.
Php page can be found at http://vscreazioni.altervista.org/prova.php and works fine.
What doesn't work is jquery side, because I'm getting parsererror as response.
Here's my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="initial-scale=1, maximum-scale=1" />
<style type="text/css">
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#button_1').click(function(e){
e.preventDefault();
e.stopPropagation();
favfunct();
});
});
function favfunct() {
$.ajax({
type: 'GET',
url: 'prova.php',
dataType: 'json',
success: function (json) {
alert("SUCCESS!!!");
},
error: function (xhr, status) {
alert(status);
},
});
}
</script>
</head>
<body>
<input id="button_1" type="button" value="push" />
</body>
</html>
I'm totally new at this stuff...any help would be appreciated
EDIT:
php code from prova.php
<?php
$conn = mysql_connect("localhost", “username”, “passwd”);
if (!$conn)
{
mysql_close($conn);
die("Problemi nello stabilire la connessione");
}
if (!mysql_select_db("my_vscreazioni"))
{
mysql_close($conn);
die("Errore di accesso al data base utenti");
}
$queryIcostanza = "SELECT SUM(iCostanza) FROM apps";
$resultIcostanza = mysql_query($queryIcostanza) or die(mysql_error());
$rowIcostanza = mysql_fetch_array($resultIcostanza);
$queryIversi = "SELECT SUM(iVersi) FROM apps";
$resultIversi = mysql_query($queryIversi) or die(mysql_error());
$rowIversi = mysql_fetch_array($resultIversi);
$queryI10numeri = "SELECT SUM(i10Numeri) FROM apps";
$resultI10numeri = mysql_query($queryI10numeri) or die(mysql_error());
$rowI10numeri = mysql_fetch_array($resultI10numeri);
$queryIcostanza4x = "SELECT SUM(iCostanza4x) FROM apps";
$resultIcostanza4x = mysql_query($queryIcostanza4x) or die(mysql_error());
$rowIcostanza4x = mysql_fetch_array($resultIcostanza4x);
$queryOndanews = "SELECT SUM(OndaNews) FROM apps";
$resultOndanews = mysql_query($queryOndanews) or die(mysql_error());
$rowOndanews = mysql_fetch_array($resultOndanews);
$queryFarmachimica = "SELECT SUM(FarmaChimica) FROM apps";
$resultFarmachimica = mysql_query($queryFarmachimica) or die(mysql_error());
$rowFarmachimica = mysql_fetch_array($resultFarmachimica);
$queryIcarrano = "SELECT SUM(iCarrano) FROM apps";
$resultIcarrano = mysql_query($queryIcarrano) or die(mysql_error());
$rowIcarrano = mysql_fetch_array($resultIcarrano);
$totale = 0;
$totaleIcostanza = $rowIcostanza['SUM(iCostanza)'];
$totaleIversi = $rowIversi['SUM(iVersi)'];
$totaleI10numeri = $rowI10numeri['SUM(i10Numeri)'];
$totaleIcostanza4x = $rowIcostanza4x['SUM(iCostanza4x)'];
$totaleOndanews = $rowOndanews['SUM(OndaNews)'];
$totaleFarmachimica = $rowFarmachimica['SUM(FarmaChimica)'];
$totaleIcarrano = $rowIcarrano['SUM(iCarrano)'];
$totale = $totaleIcostanza + $totaleIversi + $totaleI10numeri + $totaleIcostanza4x + $totaleOndanews + $totaleFarmachimica + $totaleIcarrano;
$comando = "select * from apps";
$result = mysql_query($comando) or die(mysql_error());
$ultima_data="";
while ( $dati = mysql_fetch_assoc($result) )
{
$ultima_data = $dati['data'];
}
$response = array();
$posts = array('icostanza'=> $totaleIcostanza, 'iversi'=> $totaleIversi, 'i10numeri'=> $totaleI10numeri, 'icostanza4x'=> $totaleIcostanza4x, 'ondanews'=>$totaleOndanews, 'farmachimica'=> $totaleFarmachimica, 'icarrano'=> $totaleIcarrano, 'totale'=>$totale, 'ultimo'=>$ultima_data);
$response['posts'] = $posts;
$json = json_encode($response);
echo $json;
mysql_close($conn);
?>
Edit 2:
I was having a misspelling issue. Now I got SUCCESS!!! as reported in
success: function (json) {
alert("SUCCESS!!!");
}
how can alert json content? I tried with
alert(json);
but i get an alert with [object Object]
In success block do like following to get posts.
success: function (json) {
alert(json.posts.icostanza);
},
this will alert "icostanza" value.
I've got all my html working correctly but there seems to be a problem with my php code when i try to autocomplete a field
search.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link href="css/style.css" rel="stylesheet" type="text/css">
<SCRIPT LANGUAGE="JavaScript" src="js/jquery.js"></SCRIPT>
<SCRIPT LANGUAGE="JavaScript" src="js/script.js"></SCRIPT>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<div class="main">
<div class="">scriptime</span></div>
<div id="holder">
Enter Keyword : <input type="text" id="keyword" tabindex="0"><img src="images/loading.gif" id="loading">
</div>
<div id="ajax_response"></div>
</div>
</body>
</html>
here my php code
names.php
<?php
include("Connections/myphp.php");
$keyword = $_POST['data'];
$sql = "select username from ".$users." where ".$username." like '".$keyword."%' limit 0,20";
//$sql = "select username from ".$users."";
$result = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($result))
{
echo '<ul class="list">';
while($row = mysql_fetch_array($result))
{
$str = strtolower($row['username']);
$start = strpos($str,$keyword);
$end = similar_text($str,$keyword);
$last = substr($str,$end,strlen($str));
$first = substr($str,$start,$end);
$final = '<span class="bold">'.$first.'</span>'.$last;
echo '<li><a href=\'javascript:void(0);\'>'.$final.'</a></li>';
}
echo "</ul>";
}
else
echo 0;
?>
ajax code
/*
cc:scriptime.blogspot.in
edited by :midhun.pottmmal
*/
$(document).ready(function(){
$(document).click(function(){
$("#ajax_response").fadeOut('slow');
});
$("#keyword").focus();
var offset = $("#keyword").offset();
var width = $("#keyword").width()-2;
$("#ajax_response").css("left",offset.left);
$("#ajax_response").css("width",width);
$("#keyword").keyup(function(event){
//alert(event.keyCode);
var keyword = $("#keyword").val();
if(keyword.length)
{
if(event.keyCode != 40 && event.keyCode != 38 && event.keyCode != 13)
{
$("#loading").css("visibility","visible");
$.ajax({
type: "POST",
url: "names.php",
data: "data="+keyword,
success: function(msg){
if(msg != 0)
$("#ajax_response").fadeIn("slow").html(msg);
else
{
$("#ajax_response").fadeIn("slow");
$("#ajax_response").html('<div style="text-align:left;">No Matches Found</div>');
}
$("#loading").css("visibility","hidden");
}
});
}
else
{
switch (event.keyCode)
{
case 40:
{
found = 0;
$("li").each(function(){
if($(this).attr("class") == "selected")
found = 1;
});
if(found == 1)
{
var sel = $("li[class='selected']");
sel.next().addClass("selected");
sel.removeClass("selected");
}
else
$("li:first").addClass("selected");
}
break;
case 38:
{
found = 0;
$("li").each(function(){
if($(this).attr("class") == "selected")
found = 1;
});
if(found == 1)
{
var sel = $("li[class='selected']");
sel.prev().addClass("selected");
sel.removeClass("selected");
}
else
$("li:last").addClass("selected");
}
break;
case 13:
$("#ajax_response").fadeOut("slow");
$("#keyword").val($("li[class='selected'] a").text());
break;
}
}
}
else
$("#ajax_response").fadeOut("slow");
});
$("#ajax_response").mouseover(function(){
$(this).find("li a:first-child").mouseover(function () {
$(this).addClass("selected");
});
$(this).find("li a:first-child").mouseout(function () {
$(this).removeClass("selected");
});
$(this).find("li a:first-child").click(function () {
$("#keyword").val($(this).text());
$("#ajax_response").fadeOut("slow");
});
});
});
when i try to search a name it give me an error saying : You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'where like 'ben%' limit 0,20' at line 1
$sql = "select username from ".$users." where ".$username." like '".$keyword."%' limit 0,20";
you missed the $users and $username what their values are?
2 Things:
I don't think you need data:"data="+keyword, looking at your php data:keyword will suffice.
Second,
try changing your query to:
$sql = "select username from users where username like '".$keyword."%' limit 0,20";
since your php does not seem to have $users or $username set.