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();
}
Related
I'm trying to UPDATE my php page every 5 seconds so the new data can come in into a .json file, so basically what it does, is, it gets the data from the database, and creates a .json file with this data, I need this php file to update every 5 seconds, so the .json file is updating too.
The code (JsonfileAPI.php):
<!DOCTYPE html>
<html lang="pt-br">
<head>
</head>
<body>
<?php
function get_data()
{
$servername = "nps";
$dBUsername = "nps";
$dBPassword = "nps";
$dBname = "nps";
$conn = mysqli_connect($servername, $dBUsername, $dBPassword,
$dBname);
if ($conn->connect_error){
die ("Connection failed". $conn->connect_error);
}
$sql = "SELECT * FROM dados;";
$result = mysqli_query($conn, $sql);
$json_array = array();
while($row = mysqli_fetch_assoc($result))
{
$json_array[] = array(
'AutoIncrement' => $row["AutoIncrement"],
'Aparelho' => $row["aparelho"],
'Status' => $row["Status"],
);
}
return json_encode($json_array);
}
$file_name = 'dadosjson' . '.json';
if (file_put_contents($file_name, get_data()))
{
echo $file_name. ' file created';
}
else
{
echo 'There is some error';
}
?>
<script>
$(document).ready(function () {
setInterval(function(){
$.ajax({
url: "JsonfileAPI.php",
type: 'post',
dataType: 'json',
success: function(response) {
$('.time').html(response);
}
});
}, 5000);
});
</script>
You can use this code in your application, I suggest to use separate files like index.php (for your html code) and action.php for PHP script. and don`t need .json file.
Try this, in index.php html part and javascript part like this
$(document).ready(function () {
setInterval(function(){
$.ajax({
url: "action.php",
type: 'post',
// dataType: 'json',
success: function(response) {
console.log(response);
$('.time').html(response);
}
});
}, 5000);
});
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div class="time">
</div>
</body>
</html>
Then your action.php file should be like this,
<?php
$localhost = "nps";
$username = "nps";
$password = "nps";
$dbname = "nps";
// db connection
$connect = new mysqli($localhost, $username, $password, $dbname);
// check connection
if ($connect->connect_error) {
die("Connection Failed : " . $connect->connect_error);
} else {
// echo "Successfully connected".$dbname;
}
$sql = "SELECT * FROM dados";
$result = $connect->query($sql);
$output = array('data' => array());
if ($result->num_rows > 0) {
while ($row = $result->fetch_array()) {
$output['data'][] = array(
$row[0],
$row[1],
$row[2]
);
}
}
$connect->close();
echo json_encode($output);
I have checked and it work fine. Think it will be help.
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 have a search box where user can type in a name and it will display "firstname", "username", "lastname", "email", "accountnumber". So far I have been able to get the data from database, make xml structure of it (it was one of the requirements in the school). The question is how can I echo the values that come from search box into the xml table and then output the result into the HTML table?
Code for the database (file is called ajax-search.php): (I know I am using mysql and I will fix that later)
<?php
header("Content-type: text/xml");
//Create Database connection
$db = mysql_connect("127.0.0.1","root","");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db("bank",$db);
$sSearchFor = $_GET['sSearchFor'];
$sql = "SELECT * FROM customers WHERE name LIKE '%$sSearchFor%'";
$result = mysql_query($sql, $db) or die(mysql_error());
//Create SimpleXMLElement object
$xml = new SimpleXMLElement('<xml/>');
//Add each column value a node of the XML object
while($row = mysql_fetch_assoc($result)) {
$mydata = $xml->addChild('mydata');
$mydata->addChild('Id',$row['id']);
$mydata->addChild('Name',$row['name']);
$mydata->addChild('user_name',$row['user_name']);
$mydata->addChild('last_name',$row['last_name']);
$mydata->addChild('email',$row['email']);
$mydata->addChild('account_number',$row['account_number']);
}
//Create the XML file
$fp = fopen("employeeData.xml","a+");
//$fp = fopen("php://output","a+");
//Write the XML nodes
fwrite($fp,$xml->asXML()."\r\n" );
//Close the database connection
fclose($fp);
mysql_close($db);
?>
Code for the xml, (file is called xmltable.xml):
<?xml version="1.0" encoding="utf-8"?>
<searchresults>
<name>test</name>
<username>test</username>
<lastname>test</lastname>
<email>test.test#gmail.com</email>
<accountnumber>93207802685726</accountnumber>
</searchresults>
And the final script for the ajax is on the index page:
$("#btnSearch").click(function () {
var sSearchFor = $("#txtSearch").val();
var searchLink = "ajax-search.php?sSearchFor=" + sSearchFor;
$.ajax({
type: "GET",
url: "xmltable.xml",
cache: false,
dataType: "xml",
success: function (xml) {
$(xml).find('searchresults').each(function () {
$(this).find("name").each(function () {
var name = $(this).text();
alert(name);
});
});
}
});
});
I appreciate all the help since I am really lost right now.
Cient side:
You forgot to add searchLink in your url!
$("#btnSearch").click(function () {
var searchLink = "ajax-search.php";
$.ajax({
type: "POST",
url: searchLink,
data: {sSearchFor : $("#txtSearch").val() },
cache: false,
dataType: "json",
success: function (xml) {
$(xml).find('searchresults').find('result').each(function () {
var name = $(this).find("name").text();
alert(name);
});
}
});
});
Server side:
Use this on your .PHP file. I've commented the lines that deal with file saving:
<?php
header("Content-type: text/xml");
//Create Database connection
$db = mysql_connect("127.0.0.1","root","");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db("bank",$db);
if(isset($_POST['sSearchFor']))
$sSearchFor = $_POST['sSearchFor'];
else
$sSearchFor = "";
$sql = "SELECT * FROM customers WHERE name LIKE '%$sSearchFor%'";
$result = mysql_query($sql, $db) or die(mysql_error());
//Create SimpleXMLElement object
$xml = new SimpleXMLElement('searchresults');
//Add each column value a node of the XML object
while($row = mysql_fetch_assoc($result)) {
$result= $xml->addChild('result');
$result->addChild('id',$row['id']);
$result->addChild('name',$row['name']);
$result->addChild('username',$row['user_name']);
$result->addChild('lastname',$row['last_name']);
$result->addChild('email',$row['email']);
$result->addChild('accountnumber',$row['account_number']);
}
// You can close BD now
mysql_close($db);
//Create the XML file
//$fp = fopen("employeeData.xml","a+");
//$fp = fopen("php://output","a+");
//Write the XML nodes
//fwrite($fp,$xml->asXML()."\r\n" );
//Close file
//fclose($fp);
echo $xml->asXML();
?>
Hope it helps and good luck!
I want to do is display the result of my count.php in my index page. My plan is to auto count the number of rows of user_code and display the result in the index page everytime the page is visited or viewed.
My problem is that the ajax script doesnt recieve the result of count.php to display it in count inputbox on index page.
index page:
<input type="text" value="1" name="countValue" id="countValue" style="width: 12px;" /><br />
Count: <input type="text" name="count" id="count" readonly="readonly" /><br /><br /><br />
<script>
$(document).ready(function(){
var countTimer = setInterval(
function ()
{
codeValue();
}, 500);
var $count = $('#count');
function codeValue(){
$.ajax({
url:"count.php",
type:"GET",
data: { term : $('#countValue').val() },
dataType:"JSON",
success: function(result) {
$("#count").val(result.user_code);
}
});
};
});
</script>
count.php
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";
$dbc = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo $_GET['term'];
if (isset($_GET['term'])) {
$q = $_GET['term'];
$sql = "SELECT user_code FROM students";
$query = $dbc->prepare($sql);
$query->execute();
$num_rows = $query->rowCount();
echo json_encode(array('user_code'=>$num_rows));
}
?>
Your problem
echo $_GET['term'];
This breaks the expected JSON format that your script is meant to produce. Also, you aren't even using any request parameters so I don't know why you'd even bother.
Here's your PHP, all cleaned up
<?php
try {
$dbc = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'root', '',
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$stmt = $dbc->query('SELECT COUNT(1) FROM students');
header('Content-type: application/json');
echo json_encode(['user_code' => $stmt->fetchColumn()];
} catch (Exception $e) {
http_response_code(500);
echo $e->getMessage();
}
I'd also suggest adding an error callback to your $.ajax options to handle HTTP errors.
i try your code and it works for my table i have (4) records! check your query if there is data
make sure you have jquery file in your header. I did not change anything your html file. I just create my own query on my table. then okay.
You need to create a div in indexfile and id of that div is provided in ajax file,so as to populate data form count.php in that div.
Here i will give you a similar type of example, Try it by making your related changes
index.php
<div id="content">
</div>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: 'count.php',
success: function(data) {
$('#content').html(data);
}
});
<script>
count.php
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";
$con=mysqli_connect($host,$user,$pass,$db);
$result = mysqli_query($con,"SELECT user_code FROM students");
?>
<table>//this table will be loaded in div
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td><?php echo $row['user_code']; ?></td>
</tr>
<?php
}
?>
</table>
You can also add autorefresh ajax script which will only reload only particular div after specific time interval(1 sec in below code) without reloading whole page
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#content').load('count.php').fadeIn("slow");
}, 1000); // refresh every 10000 milliseconds
</script>
What I'm trying to do is calling some database data via ajax and php. But the ajax call doesn't work, and I can't find out a solution on the web.
So here is my code:
test.php
<?php
include_once 'db_class.php';
$cat = $_GET['cat'];
$dbconn = new dbconn('localhost', 'root', 'somepsw', 'blog');
$dbconn->set_query("select * from posts where category = '".$cat."'");
echo '<br/>'.$dbconn->query.'<br/>';
$result = $dbconn->result;
$num = $dbconn->num_results;
$array = mysqli_fetch_assoc($result);
echo json_encode($array);
?>
If i type that url on browser: http://127.0.0.1:82/blog/ws/test.php?cat=css
The data returned via jsonEncode is correct, but when i'm loading it on a html page with jquery he can't read the data.
test.html
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
function ajaxCall() {
var css;
$.ajax({
url: 'test.php',
type: "GET",
data: {cat: css},
dataType: 'json',
success: function(rows)
{
alert(rows);
},
error: function() { alert("An error occurred."); }
});
}
ajaxCall();
</script>
</head>
<body></body>
</html>
Thanks in advance.
I just rewrote the php code using PDO, should be more safe now.
db.php
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpsw = "somepsw";
$dbname= "blog";
try {
#$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpsw);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $e) {
echo "Connection failed, an error occured! Please contact server administrator."; //user friendly message
getErrorsLog($e->getMessage());
}
function closeDbConn () {
$dbh = null;
}
function getErrorsLog($message) {
$file = 'dberrors.log';
$date = date("d/m : H:i :");
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new error message to the file
$current .= $date.$message;
$current .= "\r\n";
// Write the contents back to the file
file_put_contents($file, $current);
exit();
}
?>
blogdata.php
<?php
include_once "db.php";
$tableName = "posts";
$data = array();
#$view = $_GET["view"];
if (isset($_GET["view"])) {
$stmt = $dbh->prepare("SELECT * FROM $tableName WHERE category =? ORDER BY created DESC");
}
else {
try {
$stmt = $dbh->prepare("SELECT * FROM $tableName ORDER BY created DESC");
}
catch (PDOException $e) {
getErrorsLog($e->getMessage());
}
}
$stmt->bindValue(1, $view, PDO::PARAM_STR);
$stmt->execute();
$affected_rows = $stmt->rowCount(); //Rows count
if ($affected_rows == 0) {
echo "The data you looking for no longer exist, please contact the administrator.";
exit();
}
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
$data[] = $row;
}
echo json_encode($data);
closeDbConn();
?>
Your variable css has no value. You wanted to use the string 'css'. Maybe you want to be able to load other categories, too. So change your ajaxCall function to
function ajaxCall(category)
{
$.ajax({
url: 'test.php',
type: "GET",
data: {cat: category},
dataType: 'json',
success: function(rows) {
alert(rows);
},
error: function() {
alert("An error occurred.");
}
});
}
and call it using
ajaxCall('css');