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.)
Related
I have two file, test.html & test.php. I would like to display the result of an SQL query via jQuery AJAX.
test.php outputs proper JSON, but I'm not able fetch the same on clicking upon the button "Fetch Data". Is it wrong way of using AJAX?
Once fetching the data in test.html, how do I access the contents?
test.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$ajax({
url:'test.php',
type:'get',
dataType:'json',
success:function(data){
alert(data);
console.log(data['success']);
console.log(data.success);
}
});
});
});
</script>
</head>
<body>
<button>Fetch Data</button>
</body>
</html>
test.php
<?php
$dbuser="root";
$dbname="test";
$dbpass="root";
$dbserver="localhost";
// Make a MySQL Connection
$con = mysql_connect($dbserver, $dbuser, $dbpass) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());
// Create a Query
$sql_query = "SELECT ID, UserName, Status FROM user_details1";
// Execute query
$result = mysql_query($sql_query) or die(mysql_error());
$jsonArray = array();
while ($row = mysql_fetch_array($result)){
$jsonArrayItem = array();
$jsonArrayItem["ID"] = $row["ID"];
$jsonArrayItem["UserName"] = $row["UserName"];
$jsonArrayItem["Status"] = $row["Status"];
array_push($jsonArray, $jsonArrayItem);
//echo '<option value='. $row['id'] . '>'. $row['login'] . '</option>';
}
mysql_close($con);
$tableData = array(
"data" => $jsonArray
);
header('Content-Type: application/json');
echo json_encode($tableData,JSON_UNESCAPED_SLASHES);
die();
?>
How do I display/access/print the fetched result contents (AJAX section)?
Make a function like this
var dataToSend = "My Data";
$(button).on("click",function(event){
$.ajax({
method: "POST",
url: "test.php",
data: { pDataToSend: dataToSend }
}).done(function( data ) {
$('.results').empty();
$('.results').append(data);
});
});
And make a div like this
<div class="results></div>
In your PHP file you can read the POST using this code.
$foo = $_POST['pDataToSend'];
Also, your test.php file is all over the place. Use a PDO like this
//connect and setup database example
try {
$db = new PDO("mysql:host=localhost;dbname=second;port=8889","root","root");
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
} catch (Exception $e){
echo 'Could not connect to the database.105';
exit();
}
//select,insert,delete, update from database example
try{
$results = $db->prepare("SELECT * FROM articles WHERE article_id = ? AND user_id = ?");
$results->bindParam(1,$var);
$results->bindParam(2,$var2);
$results->execute();
$hold = $results->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
echo "Data could not be retrieved from the database.";
exit();
}
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 new in Ajax and JSON notation, so I'm trying to get data from differents tables of a Database, data like country names, state names, departament name, job position etc. and I've seen examples how through JSON can get data but just from a single table, can you give me a little help how can I do it with more than one table and keep it in an array.
<?php
$host = "localhost";
$user = "usuer";
$pass = "password";
$databaseName = "jsonExample";
$tableName = "variables";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$result = mysql_query("SELECT * FROM $tableName"); //query
//$array = mysql_fetch_row($result); //fetch result
if(mysql_num_rows($result) <= 0){
}else{
while($obj = mysql_fetch_row($result)){
$array[] = $obj;
}
}
echo json_encode($array);
?>
Html file:
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery.js"></script>
</head>
<body>-->
<h2> Client example </h2>
<h3>Output: </h3>
<div id="output">this element will be accessed by jquery and this text will be replaced</div>
<script id="source" language="javascript" type="text/javascript">
$(function ()
{
$.ajax({
url: 'api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var id = data[0]; //get id
var vname = data[1]; //get name
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname); //Set output element html
//recommend reading up on jquery selectors they are awesome http://api.jquery.com/category/selectors/
}
});
});
</script>
</body>
</html>
If you want to have the results from multiple queries in one array you can add each result to a key. F.i. if you querying table table1 to tablen ...
// define the array that will contain all result sets
$array = [];
// create an array for the result set coming from table 1
$array['table1']= [];
$result = mysql_query("SELECT * FROM table1");
if(mysql_num_rows($result) <= 0){
}else{
while($obj = mysql_fetch_row($result)){
$array['table1'][] = $obj;
}
}
// create an array for the result set coming from table 2
$array['table2']= [];
$result = mysql_query("SELECT * FROM table2");
if(mysql_num_rows($result) <= 0){
}else{
while($obj = mysql_fetch_row($result)){
$array['table2'][] = $obj;
}
}
::
::
// create an array for the result set coming from table n
$array['tablen']= [];
$result = mysql_query("SELECT * FROM tablen");
if(mysql_num_rows($result) <= 0){
}else{
while($obj = mysql_fetch_row($result)){
$array['tablen'][] = $obj;
}
}
// return the results formatted as json
return json_encode($array);
In javascript you can access the results for table1 with data->table1.
Tip
Use mysqli instead of mysql. It is the improved version of mysql. Check the answers for this question for some background.
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 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);
};
});