I am trying to refresh my a page if there is a change in orderStatus from database using Ajax and PHP. I set the current orderStatus as predefined data and then use Ajax to get the current orderStatus from database and finally compare if they are not the same. I want to refresh the page if they are not the same.
PHP (autorefresh.php)
<?php
$orderId = $_POST["orderId"];
$query = "SELECT * FROM orderinhomeonlinecall WHERE orderId='$orderId'";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_array($result))
{
$orderStatus = $row['orderStatus'];
$data = array(
'orderStatus' => $orderStatus
);
echo json_encode($data);
}
?>
Javascript
<script type="text/javascript" >
var predefined_val = '<?php echo $orderStatus; ?>';// your predefined value.
$.document(ready(function(){
setInterval(function(){
$.ajax({
type:"POST",
url:"autorefresh.php", //put relative url here, script which will return php
data:{orderId: <?php echo $orderId; ?>}, // if any you would like to post any data
success:function(response){
var data = response; // response data from your php script
if(predefined_val !== data){
window.location.href=window.location.href;
}
}
});
},5000);// function will run every 5 seconds
}));
The below code should work, Need to mention dataType:"json" else use JSON.stringify(data) to parse response
<script type="text/javascript">
var predefined_val = '<?php echo $orderStatus; ?>';// your predefined value.
$(document).ready(function () {
setInterval(function () {
$.ajax({
type: "POST",
url: "autorefresh.php", //put relative url here, script which will return php
data: {orderId: <?php echo $orderId; ?>}, // if any you would like to post any data
dataType: "json",
success: function (response) {
var data = response; // response data from your php script
if (predefined_val !== data.orderStatus) {
window.location.href = window.location.href;
}
}
});
}, 5000);// function will run every 5 seconds
});
</script>
I have tested this by creating two files(autorefresh.php,index.php) and test db with table and it is working for me. I think the below code would be helpful, If not please share you code, i will check and fix it.
autorefresh.php
// Create connection
$db = new mysqli("localhost", "root", "","test");
$orderId = $_POST["orderId"];
$query = "SELECT * FROM orderinhomeonlinecall WHERE orderId='$orderId'";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_array($result))
{
$orderStatus = $row['orderStatus'];
$data = array(
'orderStatus' => $orderStatus
);
echo json_encode($data);
}
?>
index.php
<?php
$orderStatus ='pending';
$orderId =1;
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
var predefined_val = '<?php echo $orderStatus; ?>';// your predefined value.
$(document).ready(function () {
setInterval(function () {
$.ajax({
type: "POST",
url: "autorefresh.php", //put relative url here, script which will return php
data: {orderId: <?php echo $orderId; ?>}, // if any you would like to post any data
dataType: "json",
success: function (response) {
var data = response; // response data from your php script
if (predefined_val !== data.orderStatus) {
window.location.href = window.location.href;
}
}
});
}, 5000);// function will run every 5 seconds
});
</script>
Related
I want to call php file from javascript, and this php file will update id=1
like this way:
javascript:
if(lastTemp >= document.getElementById("TempSet").value){
var jsonData2 =$.ajax({
url: "setpp.php",
dataType: "json",
async: false
}).responseText;
var obj2 = JSON.parse(jsonData2);
console.log(obj2);
}
else {
}
php file:
<?php
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'use';
$DATABASE_PASS = 'pass';
$DATABASE_NAME = 'database';
// Try and connect using the info above.
$db = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS,
$DATABASE_NAME);
if (!$db){
die("Connection Failed: ". mysqli_connect_error());
}
$db_update = "UPDATE setpoint_control SET status='ON' WHERE id=1";
$result = mysqli_query($db, $db_update);
?>
<?php
$data = array();
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_array($result)){
array_push($data, $row['status']);
}
}
echo json_encode($data);
?>
the code is executed and the status in database table is changed but I got error in console : SyntaxError: JSON.parse: unexpected character at line 4 column 2 of the JSON data
How can I solve this issue which I think I need to rewrite json_encode but I don't know how?
$.ajax({
type: 'post',
dataType: 'json',
cache: false,
url: 'setpp.php',
success: function (response) {
$.each(response, function(i, item) {
alert(item);
});
},
error: function () {
alert("error");
},
});
example php answer setpp.php
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
array_push($data, $row['status']);
}
die(json_encode($data));
} else {
$answer = array(
'No Records'
);
die(json_encode($answer));
}
I think the problem is the value returned by setpp.php.
remember to die(), otherwise the php answer will not be correct
I have this PHP code to select data from a database:
<?php
include './database_connect.php';
$ppid=$_POST['selectPatientID'];
$query="SELECT * FROM patient WHERE p_Id='$ppid'";
$result= mysqli_query($conn, $query);
while($row= mysqli_fetch_array($result)){
echo ($row['p_fname']);
echo ' ';
echo ($row['p_lname']);
}
?>
But I need to get the p_fname and p_lname values separately. Is there anything I could do to achieve this?
This is my jQuery:
<script>
$(document).ready(function () {
$('#selectPatientID').on('change', function (event) {
event.preventDefault();
// alert("Hi");
$.ajax({
url: "UDPatient.php",
type: 'POST',
data: {selectPatientID: $('#selectPatientID').val()},
dataType: 'html',
success: function (result) {
$('#patientName').val(result); //in here, how can I get the p_fname and p_lname separetely and put them in two different input fields?
}
});
});
});
</script>
You should try something along the lines of
<?php
include './database_connect.php';
$ppid=$_POST['selectPatientID'];
$query="SELECT * FROM patient WHERE p_Id='$ppid'";
$result= mysqli_query($conn, $query);
$row= mysqli_fetch_array($result);
echo json_encode($row);
?>
You add the query results into an array $row, which you json_encode() and echo as the result
<script>
$(document).ready(function () {
$('#selectPatientID').on('change', function (event) {
event.preventDefault();
$.ajax({
url: "UDPatient.php",
type: 'POST',
data: {selectPatientID: $('#selectPatientID').val()},
dataType: 'html',
success: function (result) {
var jsonResult = JSON.parse(result);
var p_fname = jsonResult.p_fname;
var p_lname = jsonResult.p_lname;
// whatever else
}
});
});
});
</script>
The json result can be parsed ( or the dataType set as'json' alternatively').
you have to json_encode
$row = mysqli_fetch_array($result)){
header('Content-Type: application/json');// header for json encode response
echo json_encode($row);
exit;
Your jQuery ajax code will be:
$.ajax({
url: "UDPatient.php",
type: 'POST',
data: {selectPatientID: $('#selectPatientID').val()},
dataType: 'json',// to receive data into json format
success: function (result) {
alert(result.p_fname);
alert(result. p_lname);
}
});
I have read many answers on stack overflow but I can't find an apt answer. I want to send multiple variables from php file to a javascript file. I want to use those variables later separately. So please explain with a simple example of how to get the variables from php file and how to use them separately later.
This is my js.
<script>
function here(card_numb) {
alert("pk!");
$.ajax({
url: 'details.php',
type: "GET",
dataType: 'json',
data: ({
card_number: card_numb
}),
success: function(data) {
console.log('card_number:'+data.card_number+'book_issued:'+data.book_isued);
}
});
}
I'm getting the alert 'pk!'. But $.ajax ain't working.
This is details.php
<?php
if(isset($_GET['card_number'])){
$card_number = $_GET['card_number'];
$query = "Select * from users where card_number = '".$card_number."'";
$query_run = mysqli_query($link,$query);
$row_numb =#mysqli_num_rows($query_run);
if($row_numb == 0){
echo "<div class='bdiv1'>No such number found!</div>";
} else{
$row=mysqli_fetch_assoc($query_run);
$book1 = $row['user_name'];
$arr = array('isued_book' => $book1,'card_number' => $card_number);
echo json_encode($arr);
exit();
}
}
?>
Thank you!
somthing.js - ur jspage
<script>
function here(card_numb) {
$.ajax({
url: 'details.php',
type: 'GET',
dataType: 'json',
data: {
card_number: card_numb
},
success: function(data) {
console.log('card_number:'+data.card_number+'book_issued:'+data.isued_book);
}
});
}
success: function(result){
console.log('variable1:'+result.var1+'variable2:'+result.var2+'variable3:'+result.var3);
} });
details.php
<?php
if(isset($_GET['card_number'])){
$card_number = $_GET['card_number'];
$query = "Select * from users where card_number = ".$card_number;
$query_run = mysqli_query($link,$query);
$row_numb =#mysqli_num_rows($query_run);
if(!$query_run){
echo "<div class='bdiv1'>No such number found!</div>";
} else {
$row=mysqli_fetch_assoc($query_run);
$book1 = $row['user_name'];
$arr = array('isued_book' => $book1,'card_number' => $card_number);
echo json_encode($arr);
exit();
}
if the currect value get in $row you can get the result in console
I have a small script that runs a php file in the background and gets a variable every 3 seconds and put it in a div
script in document with div
<script>
$(document).ready(function() {
setInterval(function () {
$('#statmoney').load('safe.php');
}, 3000);
});
</script>
PHP FILE (safe.php)
$sql = "SELECT * FROM users WHERE id='".$_SESSION['user_id']."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
$money = htmlspecialchars($row->money);
echo $money;
If i need to add another variable i would need to make a new document is there a easy way to go about it?
UPDATE
menu.php
<script>
$(document).ready(function() {
setInterval(function () {
var fields = ['money', 'ore', 'energy']; // array of needed fields
$.ajax({
type: "POST",
url: "menusafe.php",
data: {'fields': fields},
dataType: 'json',
success: function(response) {
// assuming that we already have divs for respective fields
fields.forEach(function(v){
console.log(response)
$("#" + v).html(response[v]);
});
}
});
}, 3000);
});
</script>
<div class="menustats"><img src="graphics/logos/moneylogo.png" class="menustatimage"><div class="menustattext" id='money'></div></div>
<div class="menustats"><img src="graphics/logos/energylogo.png" class="menustatimage"><div class="menustattext" id="energy"></div></div>
<div class="menustats"><img src="graphics/logos/orelogo.png" class="menustatimage"><div class="menustattext" id='ore'></div></div>
PHP(menusafe.php)
<?php
if ( isset($_POST['fields']) && !empty($_POST['fields']) && is_array($_POST['fields']) ){
$fields = $_POST['fields'];
$fields = (count($fields) > 1)? implode(',', $fields) : $fields;
$sql = "SELECT $fields FROM users WHERE id='".$_SESSION['user_id']."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
$result = [];
foreach($fields as $field){
$result[$field] = $row->{$field};
}
echo json_encode($result);
}
?>
Let's imagine that we want to retrieve three fields from users table : firstname, age and money. In such case it would be better to use $.post or $.ajax method:
js part:
<script>
$(document).ready(function() {
setInterval(function () {
var fields = ['firstname', 'age', 'money']; // array of needed fields
$.ajax({
type: "POST",
url: "safe.php",
data: {'fields': fields},
dataType: 'json',
success: function(response) {
// assuming that we already have divs for respective fields
fields.forEach(function(v){
$("#" + v).html(response[v]);
});
}
});
}, 3000);
});
</script>
php part: (safe.php)
if ( isset($_POST['fields']) && !empty($_POST['fields']) && is_array($_POST['fields']) ){
$fields = $_POST['fields'];
$fields = (count($fields) > 1)? implode(',', $fields) : $fields;
$sql = "SELECT $fields FROM users WHERE id='".$_SESSION['user_id']."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
$result = [];
foreach($fields as $field){
$result[$field] = $row->{$field};
}
echo json_encode($result);
}
I have a JQuery on click that sends a php query to MySql and then I want to send the data back 1 by 1 on JQuery.
But I only know how to send back results from php to JQuery as a whole.
my current JQuery:
$(function() {
$(".img_thumb_holder").on("click", function() {
$.ajax({
type: "POST",
url: "CMS/PHP/retrieveAuthorDetails.php",
success: function(data) {
alert(data);
}
});
});
});
my current php:
<?php
include 'dbAuthen.php';
$sql = "SELECT * FROM users WHERE Name = 'james'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
echo $row['UserID'];;
echo $row['EmailAddr'];
}
?>
the outputs are both UserID and EmailAddr, I don't know how to just display either the UserID or EmailAddr out only
I tried alert(data[0]), but it only displayed one letter of the result.. Any ideas on how to do this?
UPDATE: After sean's help i have the current updated code
Jquery:
$(function() {
$(".img_thumb_holder").on("click", function() {
$.ajax({
type: "POST",
dataType: "json",
url: "CMS/PHP/retrieveAuthorDetails.php",
success: function(data) {
$.each(data, function() {
var userid = data.userid;
var useremail = data.email;
// i think there something wrong with this as it will keep repeating storing the userid and email for each data.. can someone verify?
});
}
});
});
});
PHP
<?php
include 'dbAuthen.php';
$sql = "SELECT * FROM users WHERE Name = 'honwenhonwen'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
$arr = array(
"userid" => "HonWen",
"email" => "honwen#hotmail.com"
);
}
echo json_encode($arr);
?>
In your php, save the results to an array -
<?php
include 'dbAuthen.php';
$array = array(); // create a blank array
$sql = "SELECT * FROM users WHERE Name = 'james'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
// add each result to the array
$array[] = array('UserID'=> $row['UserID'], 'EmailAddr'=> $row['EmailAddr']);
}
echo json_encode($array); // json_encode() the array
?>
Then in your js/ajax you can loop through each value
$(function() {
$(".img_thumb_holder").on("click", function() {
$.ajax({
type: "POST",
url: "CMS/PHP/retrieveAuthorDetails.php",
success: function(data) {
// loop through each returned value
$.each(data, function(){
//alert each result, this is just an example as alert() for each result is not a great idea
alert("UserID:"+ this.UserID + " EmailAddr:" + this.EmailAddr);
});
}
});
});
});
jquery
$(function() {
$(".img_thumb_holder").on("click", function() {
$.ajax({
type: "POST",
dataType: "json",
url: "CMS/PHP/retrieveAuthorDetails.php",
success: function(data) {
$.each(data, function() {
var userid = data.userid;
var useremail = data.email;
// i think there something wrong with this as it will keep repeating storing the userid and email for each data.. can someone verify?
});
}
});
});
});
php
<?php
include 'dbAuthen.php';
$sql = "SELECT * FROM users WHERE Name = 'honwenhonwen'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
$arr = array(
"userid" => "HonWen",
"email" => "honwen#hotmail.com"
);
}
echo json_encode($arr);
?>