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);
Related
I need to check from the database if email exists or not by using Ajax. I am getting a response, but coming with some HTML content. I have given below my code what I have followed.
My Ajax code:
var username_state = false;
var email_state = false;
$('#username').on('blur', function(){
var username = $('#username').val();
if (username == '') {
username_state = false;
return;
}
$.ajax({
url: 'user_list.php',
type: 'post',
data: {
'username_check' : 1,
'user_name' : username,
},
success: function(response){
$("html").html($("html", response).html());
if (response == 'taken' ) {
response.find(element).remove();
alert('hi');
username_state = false;
$('#username').parent().removeClass();
$('#username').parent().addClass("form_error");
$('#username').siblings("span").text('Sorry... Username already taken');
}
else if (response == 'not_taken') {
username_state = true;
$('#username').parent().removeClass();
$('#username').parent().addClass("form_success");
$('#username').siblings("span").text('Username available');
}
}
});
});
My php Code
$db = mysqli_connect('localhost', 'root', '', 'my_assesment');
if (isset($_POST['username_check'])) {
$username = $_POST['user_name'];
// echo $username;
$sql = "SELECT * FROM user_information
WHERE user_name='".$_POST["user_name"]."'";
//echo $sql;
$results = mysqli_query($db, $sql);
if (mysqli_num_rows($results) > 0) {
//$response = true;
echo "taken";
}else{
$response = false;
echo 'not_taken';
}
This is am getting response
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<!-- jQuery -->
not_taken
Looking at the output you are receiving my guess is that the ajax request is being sent to the same page. If that is the case then initially wrap the entire username checking code within a suitable if test and ensure that any HTML buffer content is disposed of completely before sending the response to the ajax callback.
/*
Test that the request is a POST request and that
the variables you are expecting have been sent.
As you are using data sent by the client you MUST
take precautions to mitigate SQL injection attacks.
Use a Prepared statement rather than directly embedding
user supplied data in the SQL.
*/
if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
$_POST['username_check'],
$_POST['user_name']
)){
$db = mysqli_connect('localhost', 'root', '', 'my_assesment');
$sql='SELECT `user_name` FROM `user_information` WHERE `user_name`=?';
$stmt=$db->prepare( $sql );
$stmt->bind_param('s',$_POST['user_name']);
$stmt->execute();
$stmt->store_result();
$rows=$stmt->num_rows;
$stmt->close();
$response=( $rows > 0 ) ? 'taken' : 'not_taken';
# flush buffer to remove any other HTML / text content
ob_clean();
#exit completely from this logic branch
exit( $response );
}
The test page I used to try to figure out the fault in the callback was exactly as follows. Essentially rather than respecting the checkbox to do a test and querying the db a random integer determines if the status is taken or not_taken simply to test the logic in the callback.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
$_POST['username_check'],
$_POST['user_name']
)){
/*
$db = mysqli_connect('localhost', 'root', '', 'my_assesment');
$sql='SELECT `user_name` FROM `user_information` WHERE `user_name`=?';
$stmt=$db->prepare( $sql );
$stmt->bind_param('s',$_POST['user_name']);
$stmt->execute();
$stmt->store_result();
$rows=$stmt->num_rows;
$stmt->close();
*/
$rows=mt_rand(0,1);
$response=( $rows > 0 ) ? 'taken' : 'not_taken';
ob_clean();
exit( $response );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>?Username Check Test Page</title>
<script src='//code.jquery.com/jquery-latest.js'></script>
<style>
label{display:block;padding:1rem;}
.form_success{background:rgba(0,255,0,0.25)!important;}
.form_error{background:rgba(255,0,0,0.25)!important;)}
</style>
</head>
<body>
<form name='usercheck'>
<label>Username:<input type='text' id='username' name='user_name' value='geronimo' /></label>
<label>Username Check:<input type='checkbox' name='username_check' value=1 /></label>
</form>
<script>
var username_state = false;
var email_state = false;
$('#username').on('blur', function(){
var username = $('#username').val();
if (username == '') {
username_state = false;
return;
}
$.ajax({
url: location.href, // 'user_list.php' ~ same page here!
type: 'post',
data: {
'username_check' : 1,
'user_name' : username,
},
success: function(response){
alert(response);
// no idea what this is doing
// $("html").html($("html", response).html());
if (response == 'taken' ) {
// this caused issues for me... no error as such but prevented further processing
// response.find(element).remove();
alert('hi - choose another username');
username_state = false;
$('#username').parent().removeClass();
$('#username').parent().addClass("form_error");
$('#username').siblings("span").text('Sorry... Username already taken');
}
else if (response == 'not_taken') {
username_state = true;
alert('ok - that user name is fine');
$('#username').parent().removeClass();
$('#username').parent().addClass("form_success");
$('#username').siblings("span").text('Username available');
}
}
});
});
</script>
</body>
</html>
I have database consists of countries and cities.
First Case - Successfully done:
Country list gets populated in drop box on page load
City list gets populated in drop box on page load - populated city list
is based on the default country.
Second Case - Couldn't make it:
User changes country
City list will be changed according to selected country
I know i have to use jQuery/Ajax. I tried but i couldn't solve my problem due to my lack of programming experience. My list is fetched from database not XML. I just need a quick solution, i need to keep it simple and stupid.
I'm using regular PHP coding style, not Object-Oriented.
How can i do it? Any related resources will be appreciated.
$("#country").change(function(){
$('#city').find('option').remove().end(); //clear the city ddl
var country = $(this).find("option:selected").text();
alert(country);
//do the ajax call
$.ajax({
url:'getCity.php'
type:'GET',
data:{city:country},
dataType:'json',
cache:false,
success:function(data){
data=JSON.parse(data); //no need if dataType is set to json
var ddl = document.getElementById('city');
for(var c=0;c<obj.length;c++)
{
var option = document.createElement('option');
option.value = obj[c];
option.text = obj[c];
ddl.appendChild(option);
}
},
error:function(jxhr){
alert(jxhr.responseText);
}
});
});
in your getCity.php
$country = $_GET['city'];
//do the db query here
$query = "your query";
$result = mysql_query($query);
$temp = array();
while ($row = mysql_fetch_assoc($result)) {
if(empty($temp))
{
$temp=array($row['city']);
}
else
{
array_push($temp,$row['city']);
}
}
echo (json_encode($temp));
You can do that by making ajax call on change of select box value by using .change() method of jquery. api.jquery.com/change/
write data instead of obj. It works perfectly fine
index.php
<?php
require_once './db.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>StackOverFlow</title>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous">
</script>
<link rel="stylesheet" type="text/css" href="./style.css" />
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<?php
// In this part of the code i'm building the select box options
$sql = "SELECT thana FROM locations group by thana";
$stmt = $conn->prepare($sql);
$stmt->execute();
?>
<select name="Thana" class="thana-select-box">
<option></option>
<?php
while ($row = $stmt->fetch()){ ?>
<option value="<?=$row['thana']?>"><?=$row['thana']?></option>
<?php } ?>
</select>
<select name="Area" class="area-select-box">
</select>
</body>
</html>
db.php
<?php
$username = 'your username';
$password = 'your password';
$host = 'localhost';
$dbname = 'test';
$conn = new PDO("mysql:host=$host;dbname=$dbname",$username, $password
,
array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_PERSISTENT => false,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
));
get_options.php
<?php
require_once 'db.php';
$thana = $_REQUEST['thana'];
$sql = "SELECT area FROM locations where thana='$thana'";
$stmt = $conn->prepare($sql);
$stmt->execute();
$options = [];
while ($row = $stmt->fetch()){
$options[] = $row['area'];
}
echo json_encode($options);
app.js:
$(document).ready( function(){
$(document).on('change', '.thana-select-box', function(e){
let fd = new FormData();
let thana = $(this).val();
fd.append('thana', thana);
// In this part of the code according to the selected thana, we are going to fetch
// the rows from the second table Area, the php will return a json structure that contains the rows
// or more with the Area that belong to thana.
$.ajax({
url: "get_options.php",
type: "POST",
data: fd,
processData: false,
contentType: false,
complete: function (results) {
try {
let str = JSON.parse(results.responseText);
updateDOM(str);
console.log(str)
} catch (e) {
console.error(e.message);
}
},
});
});
updateDOM = (options) => {
let areaSelectBox = $('.area-select-box');
let options_dom = '';
options.map((value)=>{
options_dom += `<option value="${value}">${value}</option>`;
});
areaSelectBox.html ('');
areaSelectBox.append(options_dom);
};
});
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'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
I have database consists of countries and cities.
First Case - Successfully done:
Country list gets populated in drop box on page load
City list gets populated in drop box on page load - populated city list
is based on the default country.
Second Case - Couldn't make it:
User changes country
City list will be changed according to selected country
I know i have to use jQuery/Ajax. I tried but i couldn't solve my problem due to my lack of programming experience. My list is fetched from database not XML. I just need a quick solution, i need to keep it simple and stupid.
I'm using regular PHP coding style, not Object-Oriented.
How can i do it? Any related resources will be appreciated.
$("#country").change(function(){
$('#city').find('option').remove().end(); //clear the city ddl
var country = $(this).find("option:selected").text();
alert(country);
//do the ajax call
$.ajax({
url:'getCity.php'
type:'GET',
data:{city:country},
dataType:'json',
cache:false,
success:function(data){
data=JSON.parse(data); //no need if dataType is set to json
var ddl = document.getElementById('city');
for(var c=0;c<obj.length;c++)
{
var option = document.createElement('option');
option.value = obj[c];
option.text = obj[c];
ddl.appendChild(option);
}
},
error:function(jxhr){
alert(jxhr.responseText);
}
});
});
in your getCity.php
$country = $_GET['city'];
//do the db query here
$query = "your query";
$result = mysql_query($query);
$temp = array();
while ($row = mysql_fetch_assoc($result)) {
if(empty($temp))
{
$temp=array($row['city']);
}
else
{
array_push($temp,$row['city']);
}
}
echo (json_encode($temp));
You can do that by making ajax call on change of select box value by using .change() method of jquery. api.jquery.com/change/
write data instead of obj. It works perfectly fine
index.php
<?php
require_once './db.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>StackOverFlow</title>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous">
</script>
<link rel="stylesheet" type="text/css" href="./style.css" />
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<?php
// In this part of the code i'm building the select box options
$sql = "SELECT thana FROM locations group by thana";
$stmt = $conn->prepare($sql);
$stmt->execute();
?>
<select name="Thana" class="thana-select-box">
<option></option>
<?php
while ($row = $stmt->fetch()){ ?>
<option value="<?=$row['thana']?>"><?=$row['thana']?></option>
<?php } ?>
</select>
<select name="Area" class="area-select-box">
</select>
</body>
</html>
db.php
<?php
$username = 'your username';
$password = 'your password';
$host = 'localhost';
$dbname = 'test';
$conn = new PDO("mysql:host=$host;dbname=$dbname",$username, $password
,
array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_PERSISTENT => false,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
));
get_options.php
<?php
require_once 'db.php';
$thana = $_REQUEST['thana'];
$sql = "SELECT area FROM locations where thana='$thana'";
$stmt = $conn->prepare($sql);
$stmt->execute();
$options = [];
while ($row = $stmt->fetch()){
$options[] = $row['area'];
}
echo json_encode($options);
app.js:
$(document).ready( function(){
$(document).on('change', '.thana-select-box', function(e){
let fd = new FormData();
let thana = $(this).val();
fd.append('thana', thana);
// In this part of the code according to the selected thana, we are going to fetch
// the rows from the second table Area, the php will return a json structure that contains the rows
// or more with the Area that belong to thana.
$.ajax({
url: "get_options.php",
type: "POST",
data: fd,
processData: false,
contentType: false,
complete: function (results) {
try {
let str = JSON.parse(results.responseText);
updateDOM(str);
console.log(str)
} catch (e) {
console.error(e.message);
}
},
});
});
updateDOM = (options) => {
let areaSelectBox = $('.area-select-box');
let options_dom = '';
options.map((value)=>{
options_dom += `<option value="${value}">${value}</option>`;
});
areaSelectBox.html ('');
areaSelectBox.append(options_dom);
};
});