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.
Related
i have this code:connection to database
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$conn = new mysqli("localhost", "root", "", "jquery");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
now i already have data indatabase in table called city witch it have only id and desc and this is the code
if (isset($_POST['city'])) {
$sql = "SELECT * FROM city";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$results = [];
while($row = $result->fetch_assoc()) {
$results[] = $row;
}
echo json_encode($Results);
}
else
{
echo "empty";
}
}
here is the html part:
<select required="required" id="city">
<option disabled selected value=''> select a city </option>
</select>
and here is the function:
function city() {
$.ajax({
"url": "divs.php",
"dataType": "json",
"method": "post",
//ifModified: true,
"data": {
"F": ""
}
})
.done(function(data, status) {
if (status === "success") {
for (var i = 0; i < data.length; i++) {
var c = data[i]["city"];
$('select').append('<option value="'+c+'">'+c+'</option>');
}
}
})
.always(function() {
});
}
so the problem is that there is nothing in select list its always empty, any help? thank u
One small mistake is here:
You are using
echo json_encode($Results);
instead of
echo json_encode($results);
In PHP variable names are case sensitive. So, use proper case for all the variables.
You are not getting the response data in HTML <SELECT> TAG here is what you can do.
image to table
HTML FILE CODE:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<form action="" method="post">
<select>
</select>
</form>
<script>
$(document).ready(function(){
city();
});
function city(){
$.ajax({
type:'POST',
url: 'divs.php',
data: {city:1},
success:function(data){
var res = JSON.parse(data)
for(var i in res){
var showdata = '<option value="'+res[i].city_name+'">'+res[i].city_name+'</option>';
$("select").append(showdata);
}
}
});
}
</script>
</body>
</html>
HERE IS THE PHP CODE
`
<?php
$conn = new mysqli('localhost','root','','demo');
if($conn->connect_error){
die ("Connection Failed".$conn->link->error);
}
if(isset($_POST['city'])){
$sql = "SELECT * FROM city";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$results[] = $row;
}
echo json_encode($results);
}
else
{
echo "no city available";
}
}
?>
`
HERE IS THE OUTPUT IMAGE
You have used $results but while echoing you are using $Results which is a different variable so use,
echo json_encode($results);
Also, you are telling that city has only id and desc so in JS code use desc instead of city
$.ajax({
type:'POST',
url: 'divs.php',
data: {city:1},
success:function(data) {
var res = JSON.parse(data);
$(res).each(function(){
var c = this.city_name; // use city_name here instead of city
$('select').append('<option value="'+c+'">'+c+'</option>');
});
}
});
This question already has answers here:
jquery serialize and multi select dropdown
(6 answers)
Get the values of 2 HTML input tags having the same name using PHP
(4 answers)
Closed 6 years ago.
I want to change the status in the database, with a select dropdown field.
I am sending with ajax. The first row is always working, but with multiple data i cant update the second, third..etc
I tried with serialize(), but its not working.
select from database:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".allbooks").change(function(){
var allbooks = $(this).val();
var dataString = "allbooks="+allbooks;
$.ajax({
type: "POST",
data: dataString,
url: "get-data.php",
success: function(result){
$("#show").html(result);
}
});
});
});
</script>
</head>
<body>
<?php
define("HOST","localhost");
define("USER","root");
define("PASSWORD","");
define("DATABASE","hotel");
$euConn = mysqli_connect(HOST, USER, PASSWORD, DATABASE);
$selectRooms = "SELECT * FROM proba WHERE status='inRoom'";
$resultRooms = mysqli_query($euConn,$selectRooms);
if (mysqli_num_rows($resultRooms) > 0) {
echo "<div id='reserved' align='center'>";
While ($row = mysqli_fetch_array($resultRooms)) {
echo $row[1];
echo $row[0];
?>
<select name="allbooks" id="allbooks">
<option name="years">Choose</option>
<?php
for($i=1; $i<=19; $i++)
{
echo "<option value=".$i.">".$i."</option>";
}
?>
</select><br />
<?php }
}
else
echo "<h4>nothing in the db</h4></div>";
?>
<div id="show">
</div>
</body>
</html>
and getting the results:
if(!empty($_POST["allbooks"])) {
var_dump($_POST);
$id = 2;
//echo $_POST['modelS'];
$room = $_POST['allbooks'];
$sql2 = "UPDATE proba SET room='$room' WHERE id_reservation='$id'";
$query = mysqli_query($euConn, $sql2);
var_dump($query);
}
How to change, or what would be a simple solution? Thanks for the help.
You have multiple select elements on the rendered page with the id allbooks That's wrong, IDs must be unique. You'll want to change those to a class and use $(".allbooks").change(function(){ ....
As far as sending the row id to the server with the update, you'll need to first add the row id to the select box so you can retrieve it later, something like '<select name="allbooks" class="allbooks" data-row-id="' . $row['id_reservation'] . '"> would work.
I would also recommend splitting the work up into several functions to better organize your code (classes would be even better)
It's hard to test without access to the DB, but this should do it for you. Note that I have the update function on the same page and updated the ajax url property to '' which will send the data to a new instance of the current page to handle the update.
<?php
require_once ("db_config.php");
function updateRoom($euConn, $newRoomVal, $id)
{
$stmt = $euConn->prepare("UPDATE proba SET room=? WHERE id_reservation=?");
$stmt->bind_param('ii', $newRoomVal, $id);
/* execute prepared statement */
$stmt->execute();
/* close statement and connection */
$affectedRows = mysqli_stmt_affected_rows($stmt) > 0;
$stmt->close();
return $affectedRows;
}
function getRooms($euConn)
{
$selectRooms = "SELECT * FROM proba WHERE status='inRoom'";
$resultRooms = mysqli_query($euConn,$selectRooms);
$rows = mysqli_fetch_all($resultRooms,MYSQLI_ASSOC);
return count($rows) < 1 ? '<h4>nothing in the db</h4></div>' : createSections($rows);
}
function createSections($rows)
{
$sections = [];
foreach( $rows as $row){
$options = [];
for ($i = 1; $i <= 19; $i++)
$options[] = "<option value=" . $i . ">" . $i . "</option>";
$options = implode('', $options);
$select = '<select name="allbooks" class="allbooks" data-row-id="' . $row['id_reservation'] . '"><option value="">Choose</option>' . $options . '</select><br/>';
// .. build all your other row elements here....
$section = 'some other compiled html'.$select;
$sections[]=$section;
}
return implode('', $sections);
}
$euConn = mysqli_connect(HOST, USER, PASSWORD, DATABASE);
if(isset($_POST["allbooks"]) && $_POST["allbooks"] !='') {
$updated = updateRoom($euConn,$_POST["allbooks"],$_POST["rowId"] );
echo json_encode(['success'=>$updated]);
exit;
}
$pageSections = getRooms($euConn);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".allbooks").change(function(){
var $this = $(this);
var allbooks = $this.val();
var rowId = $this.data('row-id');
var dataString = "allbooks="+allbooks+'&rowId='+rowId;
$.ajax({
type: "POST",
data: dataString,
url: "",
success: function(result){
$("#show").html(result);
}
});
});
});
</script>
</head>
<body>
<div id='reserved' align='center'>
<?php echo $pageSections ?>
<div id="show">
</div>
</body>
</html>
Guys i have a problem actually my php code is correct but i dont know why it display undefined into my client side script. Could somebody help me
here is my api.php this is where i put my php
<?php
$dbcon = mysqli_connect("localhost", "root", "", "orms") or die("Server not available" . mysql_error());
$data = array();
$result = mysqli_query($dbcon,"SELECT * FROM cottages") or die(mysqli_error()); //query
//$array = mysqli_fetch_row($result);
$data = array();
while($row = mysqli_fetch_assoc($result))
{
$data[] = $row;
}
echo json_encode( $data ) //fetch result
?>
here is my client.php code
<?php
$dbcon = mysqli_connect("localhost", "root", "", "orms") or die("Server not available" . mysql_error());
?>
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery.js"> </script>
</head>
<body>
<h2> Client example </h2>
<h3>Output: </h3>
<div id="output"></div>
<script id="source" language="javascript" type="text/javascript">
$(function ()
{
$.ajax({
url: 'api.php', data: "POST", dataType: 'json', success: function(rows)
{
for (var i in rows)
{
var row = rows[i];
var cot_id = row[0];
var image = row[1];
$('#output').append("<b>cottage: </b>"+cot_id+"<b> image: </b>"+image)
.append("<hr />");
}
}
});
});
</script>
</body>
</html>
Thanks for your help in advance..
You're using mysqli_fetch_assoc, so the row will be an associative array, which turns into a Javascript object. But in the Javascript code you're accessing row as if it's an array, not an object. You need to use the column names:
var cot_id = row.cot_id;
var image = row.image;
(I'm just guessing the column names, because you used SELECT * so I can't see the actual names in your table.)
I'm building a small online order system for a restaurant. My code for shoping card looks like this:
<?php
// Košarica
function ShopKosarica(){
global $link;
$UkupnoZbroj = 0;
$KosaricaSession = $_SESSION['ime'];
$rezultat = mysqli_query($link, "SELECT * FROM shop_kosarica WHERE KosaricaSession='$KosaricaSession' AND KosaricaKolicina<>0 ORDER BY KosaricaID ASC");
$num_results = mysqli_num_rows($rezultat);
if ($num_results==0){
echo "<h2><strong>Košarica je prazna</strong></h2>";
}else{
while ($redak = mysqli_fetch_array($rezultat)){
$ArtikalID = $redak['KosaricaArtikal'];
$rezultat_artikal = mysqli_query($link, "SELECT * FROM shop_artikal WHERE ArtikalID='$ArtikalID'");
$redak_artikal = mysqli_fetch_array($rezultat_artikal);
if ($redak['KosaricaVelicina']=='jumbo'){
$Cijena = $redak_artikal['ArtikalCijena2'];
} else {
$Cijena = $redak_artikal['ArtikalCijena1'];
}
$Kolicina = $redak['KosaricaKolicina'];
$Zbroj = $Cijena * $Kolicina;
$Zbroj = number_format((float)$Zbroj, 2, '.', '');
$UkupnoZbroj += $Zbroj;
$UkupnoZbroj = number_format((float)$UkupnoZbroj, 2, '.', '');
?>
<form class="ShopKosaricaBox" method="post">
<input type="hidden" id="KosaricaID" name="KosaricaID" value="<?=$redak['KosaricaID']?>">
<div class="MarginBottom15">
<input type="text" id="KosaricaKolicina" name="KosaricaKolicina" value="<?=$redak['KosaricaKolicina']?>" maxlength="2"> x <?=$redak_artikal['ArtikalNazivHr']?> (<?=$redak['KosaricaVelicina']?>) - <?=$Zbroj?> kn
</div>
<div class="right MarginBottom15">
<a onclick="ShopPromjena();">Promjeni</a> <a style="background:#c94e11;" onclick="ShopBrisanje();">Obriši</a>
</div>
<div class="clear"></div>
</form>
<script type="text/javascript">
function ShopPromjena() {
$(document).ready(function(){
var str = $(".ShopKosaricaBox").serialize();
$.ajax({
type: "POST",
url: "/funkcije?akcija=promjena&KosaricaID=<?=$redak['KosaricaID']?>",
data: str,
success: function(str){
alert( "Uspješno ste promjenili količinu!" );
}
});
return false;
});
}
function ShopBrisanje() {
$(document).ready(function(){
var str = $(".ShopKosaricaBox").serialize();
$.ajax({
type: "POST",
url: "/funkcije?akcija=brisi&KosaricaID=<?=$redak['KosaricaID']?>",
data: str,
success: function(str){
alert( "Uspješno ste obrisali jelo!" );
}
});
return false;
});
}
</script>
<?php
} ?>
<h1 class="MarginBottom25" style="font-size:25px;">Ukupno: <strong><?=$UkupnoZbroj?> kn</strong></h1>
<?php }
}
?>
And I put data in mysql via Ayax, this is the javascript:
$(document).ready(function(){
$(".ShopPonudaBox").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "/funkcije?akcija=dodaj",
data: str,
success: function(str){
alert( "Uspješno ste dodali jelo!" );
$('#KosaricaBox').load("/include/funkcije.php?funkcija=ShopKosarica");
return false;
}
});
return false;
});
});
and php code;
if ($_GET['akcija']=="dodaj") {
if ($_POST['KosaricaKolicina']<>0){
$KosaricaSession = $_SESSION['ime'];
$KosaricaArtikal = clean($link, $_POST['ArtikalID']);
$KosaricaKolicina = clean($link, $_POST['KosaricaKolicina']);
$KosaricaVelicina = clean($link, $_POST['KosaricaVelicina']);
$provjera = mysqli_query($link, "SELECT * FROM shop_kosarica WHERE KosaricaSession='$KosaricaSession' AND KosaricaArtikal='$KosaricaArtikal' AND KosaricaVelicina='$KosaricaVelicina'");
$num_results = mysqli_num_rows($provjera);
if ($num_results==0){
$result = mysqli_query($link, "INSERT INTO shop_kosarica (KosaricaSession, KosaricaArtikal, KosaricaKolicina, KosaricaVelicina) VALUE ('$KosaricaSession', '$KosaricaArtikal', '$KosaricaKolicina', '$KosaricaVelicina')");
//header("Location: /online-narudzba#Shop");
} else {
$redak_provjera = mysqli_fetch_array($provjera);
$KosaricaID = $redak_provjera['KosaricaID'];
$result = mysqli_query($link, "UPDATE shop_kosarica SET KosaricaKolicina=KosaricaKolicina+$KosaricaKolicina WHERE KosaricaID='$KosaricaID'");
//header("Location: /online-narudzba#Shop");
}
} else {
//header("Location: /online-narudzba#Shop");
}
}
I tried with this method I found here
$('#KosaricaBox').load("/include/funkcije.php?funkcija=ShopKosarica");
$funkcija = $_GET["funkcija"];
if ($funkcija == "ShopKosarica") {
echo ShopKosarica();
}
but keep getting errors
Notice: Undefined variable: _SESSION in
H:\Dropbox\htdocs\include\funkcije.php on line 47
Warning: mysqli_query() expects parameter 1 to be mysqli, null given
in H:\Dropbox\htdocs\include\funkcije.php on line 48
Add
session_start();
and connect database
at the beginning of your page before any HTML
You will have something like :
$con=mysqli_connect("localhost","xxxx","xxxx","xxxxx");
//check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL:" . mysqli_connect_error();
}
session_start();
include("inc/incfiles/header.inc.php")?>
<html>
<head>
<meta http-equiv="Content-Type" conte...
Don't forget to remove the space you have before
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.