Reload data from database without refreshing page - javascript

My Ajax successfully update some information in database and as a result he should update one element, which shows this information. But it doesn't. However, after refreshing page, which cause reconnecting to db, information updating. Here is the function:
function topUpTheBalance(){
var d = document.getElementById("numberForm").value;
$.ajax({
type: 'POST',
url: 'handler.php',
data: {
'topUpBalance':d,
},
success: function () {
var k = document.getElementById("balanceNumber");
k.innerHTML ="Your balance: "+ <?php echo $userRow['userBalance']; ?>;
}
}
);
}
and the handler.php
<?php
ob_start();
session_start();
require_once 'dbconnect.php';
if( !isset($_SESSION['user']) ) {
header("Location: index.php");
exit;
}
$res=mysqli_query($link, "SELECT * FROM users WHERE userId=".$_SESSION['user']);
$userRow=mysqli_fetch_array($res);
//$link = mysqli_connect("localhost","username","password", "users");
$bal = $userRow['userBalance']+$_POST['topUpBalance'];
if($stmt = mysqli_prepare($link, "UPDATE users SET userBalance = ? WHERE userId = ?")){
mysqli_stmt_bind_param($stmt, "di", $bal, $userRow['userId']);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $result);
mysqli_stmt_fetch($stmt);
mysqli_stmt_close($stmt);
}
mysqli_close($link);
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
<?php ob_end_flush(); ?>
Can anyone suggest me how to update this information without refreshing the page?

The issue is that you are trying to run php in the client side when you wrote k.innerHTML="string"+php code
You should instead produce an output in the php file you request to and retrieve that output and put it in here.
https://www.w3schools.com/jquery/jquery_ajax_get_post.asp
The link explains how to send data to server through POST and get data from server through GET.

there is no detail information to help you but the first thing i noticed is your AJAX call, to get data you need to call it through GET type:
$.ajax({
'url': 'getdata.php',
'type': 'GET',
'dataType': 'json',
'data': {'topUpBalance':d},
'success': function(data) {
// if the request calls properly
},
'error': function(data) {
// if the request fails.
}
});

The main thing is you should throw output from php side but you have not sent output and You should use isset($_POST['topUpBalance']) and then go to other process for example :-
if(isset($_POST['topUpBalance'])){
$res=mysqli_query($link, "SELECT * FROM users WHERE
userId=".$_SESSION['user']);
$userRow=mysqli_fetch_array($res);
$bal = $userRow['userBalance'] + $_POST['topUpBalance'];
if($stmt = mysqli_prepare($link, "UPDATE users SET userBalance = ?
WHERE userId = ?")){
mysqli_stmt_bind_param($stmt, "di", $bal, $userRow['userId']);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $result);
//Send output echo ...... ;
mysqli_stmt_fetch($stmt);
mysqli_stmt_close($stmt);
}
mysqli_close($link);
}
In jquery side :-
receive data using parameter
function topUpTheBalance(){
var d = document.getElementById("numberForm").value;
$.ajax({
type: 'POST',
url: 'handler.php',
data: {
'topUpBalance':d,
},
success: function (data) {
// use sent data or unsent data for processing
}
}
);
}

Related

Refresh page if there is change in database

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>

json_encode prints data in html

I'm trying to pass Database table from PHP (using Object-Oriented approach) to Javascript using Ajax (json_encode) which I've done successfully. The problem, however, is that the values that are inside the $data variable are printed in my body tag with a huge whitespace after it.
Server Side:
<?php
require_once "Database.php";
Class Product extends Database
{
public function getAllProducts(){
$sql = $this->connectDB()->query("SELECT * FROM product");
while($row = $sql->fetch()) {
$data[] = $row;
}
echo json_encode($data);
}
}
$p = new Product();
$p->getAllProducts();
?>
Client side:
$(function() {
getProductData();
});
function getProductData(){
$.ajax({
url: "Product.php",
type: "get",
dataType: "json",
success: successAjax,
error: errorAjax,
complete: function(xhr, status) {
console.log(xhr);
console.log(status);
}
});
}
function successAjax($jsonarray){
console.log($jsonarray);
}
Output (Note that body tags aren't being outputted):
<body>
"[{"id":"1","0":"1","name":"john","1":"john"},
{"id":"2","0":"2","name":"bob","1":"bob"}]"
</body>
Is there any way to prevent echo json_encode from printing data in HTML if all I want to do is pass it from PHP to javascript?
Try to send out the json http header in first place on product.php
header('Content-Type: application/json');

How to get id and type in php foreach loop and send to server via ajax?

So i have 2 files index.php and changeLikeDislike.php. I think the issue is where javascript is trying to get the type and id but I do not know how I would go about that. My javascript function is being called in the foreach->li->divs. It was working before like this: data: dataString, but I added schoolId into data of ajax as well so it's like this now data: {dataString:dataString, schoolId:schoolId},
index.php
<?php
$last_id = 0;
foreach ($list as $rs) {
$last_id = $rs['id']; // keep the last id for the paging
?>
<li>
<div style="width:100%; color:#000;">
<?php echo '<div class="product_like thumb-div"><img src="like.png" class="rating-image " onclick=changeLikeDislike("like","'.$rs['id'].'")> <br><span id="product_like_'.$rs['id'].'">'.$rs['pLike'].'</span></div>';?>
<?php echo '<div class="product_dislike"><img src="dislike.png" class="rating-image" onclick=changeLikeDislike("dislike","'.$rs['id'].'")><br> <span id="product_dislike_'.$rs['id'].'">'.$rs['pDislike'].'</span></div>';?>
</div>
</li>
<?php
}
?>
<script type="text/javascript">
//begin like and dislike
function changeLikeDislike(type,id){
var dataString = 'id='+ id + '&type=' + type;
$.ajax({
type: "POST",
url: "changeLikeDislike.php",
data: {dataString:dataString, schoolId:schoolId},
cache: false,
success: function(result){
if(result){
console.log('working');
}
}
});//end ajax
}
schoolId works in data but not dataString in ajax How would i go about grabbing those. My php file for reference:
//checks if school page id was brought and stores into variable
if (isset($_POST['schoolId'])) {
$schoolIdFinal = $_POST['schoolId'];
}else {
echo "nope";
}
if (isset($_POST['type'])) {
$type = $_POST['type'];
}else {
echo "nope type";
}
if (isset($_POST['id'])) {
$id = $_POST['id'];
}else {
echo "nope id";
}
my page is echoing out "nope type nope id"
Please change
data: {dataString:dataString, schoolId:schoolId},
to
data: {type:type, id:id, schoolId:schoolId},
to match the params to your PHP script.
data can either be a query string (like your dataString) OR a json struct (like {type:type, id:id, schoolId:schoolId}).
See the documentation of jQuery.ajax():
"The data option can contain either a query string of the form key1=value1&key2=value2, or an object of the form {key1: 'value1', key2: 'value2'}."
see http://api.jquery.com/jquery.ajax/
The issue is in the data bracket. change
data: {dataString:dataString, schoolId:schoolId}
to
data: {dataString:'dataString', schoolId:'schoolId'}
next time do a print_r of $_REQUEST or $_POST to see what fields are being recognized and in this case it looks like its not detecting anything.

Pass a variabile from php to js via JSON

At the lessons i learn how to pass result from a sql request to js via JSON/AJAX. I need the value of the row from this request in my js but it doesnt work. Via console i have an error: Uncaught SyntaxError: Unexpected token <
part of PHP:
<?php
//get all the course from db and reply using json structure
//connection to db
$mysqli = new mysqli("localhost", "root", "", "my_hyp");
$id = $_POST['id'];
if (mysqli_connect_errno()) { //verify connection
exit(); //do nothing else
}
else {
# extract results mysqli_result::fetch_array
$query = " SELECT * FROM course WHERE course_category='$id'";
//query execution
$result = $mysqli->query($query);
//if there are data available
if($result->num_rows >0)
{
$myArray = array();//create an array
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myArray[] = array_map('utf8_encode', $row);
}
$response = array();
$response['rows'] = $row;
$response['query'] = $myArray;
echo json_encode($response);
}
//free result
$a=num_rows;
$result,$a->close();
//close connection
$mysqli->close();
}
?>
first part of Script:
$.ajax({
method: "POST",
//dataType: "json", //type of data
crossDomain: true, //localhost purposes
url: "./query/cate_has_courses.php", //Relative or absolute path to file.php file
data: {id: i},
success: function(response) {
console.log(JSON.parse(response));
var course=JSON.parse(response.query);
var row=JSON.parse(response.rows);
Seem you use JSON.parse in wrong way.
The JSON.parse must be done one time only. The result of JSON.parse is store in course the the access to the data is due by response.query or respons.row .. and so on and not by JSON.parse(respose.query)

Getting a value from Javascript in PHP [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
I am not very experienced in web programming and am attempting to run a script which updates my database.
<script>
function myFunction() {
var texts = document.getElementById("content").textContent;
alert(texts)
<?php
include_once 'accounts/config.php';
$text = ...;
$tbl_name='enemies'; // Table name
$query = "UPDATE enemies SET text=('$text') WHERE id=1";
$result = mysql_query($query) or die(mysql_error());
?>
}
</script>
I have no idea what to put in the $text section as shown with $text = ...; in order to get the variable texts from above.
EDIT
I have updated my code but the function does not seem to be accessing the PHP file. I am using a button to call the function and I have also tested it so i know the function is being called. My file is called update.php and is in the same directory as this file.
<button onclick="myFunction()">Click This</button>
<script>
function myFunction() {
var texts = document.getElementById("content").textContent;
$.ajax({
url: "update.php",
type: "POST",
data: {texts:texts},
success: function(response){
}
});
}
</script>
you can post your $texts value to other php page using ajax and get the variable on php page using $_POST['texts'] and place update query there and enjoy....
function myFunction() {
var texts = document.getElementById("content").textContent;
$.ajax({
url: 'update.php',
type: "POST",
data: {texts:texts},
success: function(response)
{
}
});
And your php file will be named as update.php
<?php
include_once 'accounts/config.php';
$text =$_POST['texts'];
$tbl_name='enemies'; // Table name
$query = "UPDATE `enemies` SET `text`='".$text."' WHERE `id`=1";
$result = mysql_query($query) or die(mysql_error());
?>
PHP runs on the server and then generates output which is then returned to the client side. You can't have a JavaScript function make a call to inlined PHP since the PHP runs before the JavaScript is ever delivered to the client side.
Instead, what you'd need to do is have your function make an AJAX request to a server-side PHP script that then extracts the data from the request body and then stores it in the database.
PHP: "/yourPhpScript.php"
<?php
include_once 'accounts/config.php';
$text = $_POST['data'];
$tbl_name='enemies'; // Table name
$query = "UPDATE enemies SET text='".$text.'" WHERE id=1";
$result = mysql_query($query) or die(mysql_error());
?>
JavaScript:
function myFunction() {
var texts = document.getElementById("content").textContent;
alert(texts);
// append data as a query string
var params = 'data='+texts;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
// when server responds, output any response, if applicable
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
// replace with the filename of your PHP script that will do the update.
var url = '/yourPhpScript.php';
xmlhttp.open("POST", url, true);
xmlhttp.send(params);
}
A word of caution: This is not a safe, production-friendly way of updating data in your database. This code is open to SQL injection attacks, which is outside the scope of your question. Please see Bobby Tables: A guide to preventing SQL injection if you are writing code that will go into production.
You are wrong in approach
You should use ajax to post 'texts' value to your php script
https://api.jquery.com/jquery.post/ and create separate php file where you will get data from ajax post and update DB
javascript:
<script>
function myFunction() {
var texts = document.getElementById("content").textContent;
$.ajax({
type: "POST",
url: "update.php",
data: "texsts=" + texts,
success: success
});
}
</script>
update.php
<?php
include_once 'accounts/config.php';
$text = $_POST['texts'];
$tbl_name='enemies'; // Table name
$query = "UPDATE enemies SET text=('$text') WHERE id=1";
$result = mysql_query($query) or die(mysql_error());
?>
i will use PDO if i was you, what you do mysql_query are outdated, if you use my framework https://github.com/parisnakitakejser/PinkCowFramework you can do the following code.
<?php
include('config.php');
$text = $_POST['text'];
$query = PinkCow\Database::prepare("UPDATE enemies SET text = :text WHERE id = 1");
$bindparam = array(
array('text', $text, 'str')
);
PinkCow\Database::exec($query,$bindparam);
$jsonArray = array(
'status' => 200
);
echo json_encode($jsonArray);
?>
place this code in jsonUpdateEnemies.php file and call it width jQuery
<script>
function myFunction(yourText) {
$.post( 'jsonUpdateEnemies.php', {
'text' : yourText
}, function(data)
{
alert('Data updated');
},'json');
}
</script>
its a little more complex then you ask about, but its how i will resolved your problem, :)

Categories