Ajax - Check for database update - php

Im making a autobuy system. I have a invoice page that show with default - payment processing. I have made it so that when they actually buy via coinpayments.net, it updates the database to status 1. I want to make it so that when the status changes to 1 in the database, it updates the invoice page without refreshing and says "Payment Status: Completed". I have some ajax and php code but it doesn't seem to be working. I update the database status to 1 and no text changes on my page. I have a timer interval that should be updating every 2 seconds but something is wrong. Please help.
My HTML status code
<input type="hidden" id="order_numb" value="<?php echo $_SESSION['succ_itm_id']; ?>">
<div id="payment" style="text-align: center;">
Status<br><img src="../img/processing/payment_proc.gif"><br>Payment Pending
</div>
My AJAX code
<script>
function send_data() {
var order_id = $('#order_numb').val();
$.ajax ({
type: "POST",
url: '../rld_payment.php',
data: { order_num: order_id },
success:function(data)
{
$('#payment').innerHTML = 'Status<br><b>Payment Completed!</b><br><b>Redirecting</b> ...';
}
});
}
send_data();
setInterval(send_data, (2 * 1000));
</script>
My PHP code to check status
<?php
include('conf/db_.php');
$order_id = mysqli_real_escape_string($con, $_POST['order_num']);
$order_status = mysqli_query($con, "SELECT `status` FROM `orderinfo` WHERE `order_id` = '$order_id'") or die(mysqli_error($con));
if($order_status == 1)
{
echo 'Status<br><b>Payment Completed!</b><br><b>Redirecting</b> ...';
return true;
}
?>

Why do you need to store session variable in a hidden field if you have it already stored in a session that can be easily accessed on any other page? Unless you have a valid reason for doing so, just use $_SESSION['succ_itm_id'] in your payment script.
Second, your query only selects the record NOT updates the record.
I would simply do,
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include 'conf/db_.php';
$order_id = $_SESSION['succ_itm_id'];
$result = mysqli_query($con, "UPDATE orderinfo SET status = 1 WHERE order_id = $order_id");
if ($result) {
echo 'Payment Status: Completed';
}
?>
In your JavaScript code, you would then not need to pass anything.
Note that the response (what you echo'd in your payment script) is stored in the data variable, so you can use it to add in the HTML.
Note also that $(selector) is always a jQuery object, not a native JavaScript element. A jQuery object doesn't have a property innerHTML but has a convenient .html() method.
<script>
function send_data() {
/*$.ajax({
type: 'POST',
url: '../rld_payment.php',
success: function (data) {
$('#payment').html(data);
}
});*/
console.log('sending data');
// shorthand method to $.ajax()
$.post('../rld_payment.php', function (data) {
console.log('receiving data', data);
$('#payment').html(data);
});
}
send_data();
setInterval(send_data, 2 * 1000);
</script>

Thank you everyone for all your help! I took the jQuery code from #Mikey and the PHP code from #Kark92 which put together, both worked superbly.
My final, working code is below:
HTML
<div id="payment" style="text-align: center;"></div>
jQUERY / AJAX
<script>
function send_data() {
console.log('sending data');
$.post('../inc/rld_payment.php', function (data) {
console.log('receiving data', data);
$('#payment').html(data);
});
}
send_data();
setInterval(send_data, 2000);
</script>
PHP
<?php
session_start();
include 'conf/db_.php';
$order_id = $_SESSION['succ_itm_id'];
$sql = "SELECT status FROM orderinfo WHERE order_id = '$order_id'";
$results = mysqli_query ($con, $sql );
if ( !$results ) return false;
$row = mysqli_fetch_assoc( $results );
$order_status = $row ['status'];
if($order_status == 1)
{
echo 'Payment Status: Completed';
}
else
{
echo 'Status<br><img src="../img/processing/payment_proc.gif"><br>Payment Pending';
}
?>

You have an error on this statement :
if($order_status == 1)
mysql_query() returns a resource on success, or FALSE on error. So it will never return 1, then the statement was FALSE all the the time.
You must do something like this :
$results = mysql_query ($conn, $sql );
if ( !$results ) return false;
$row = mysql_fetch_assoc( $results );
$order_status = $row ['status'];

Related

There is any way to get status change in real time using AJAX jQuery?

I'm trying to get a status from database using jQuery AJAX. For this status I have 3 options, if the status is pending I want to keep loading the request, if I go to database and change this status to success or error, the loading request will interrupt and return the status(error and success status).
jQuery Code
$.ajax({
type:'get',
url:getStatus.php?record_id=50,
success: function(e){
console.log(e)
}
});
PHP Code - getStatus.php
<?php
require_once (class/class.php');
$stat = new Stat();
$record_id= $_GET['record_id'];
$status = $stat->getStatus($record_id);
echo $status;
PHP Code - geStatus() Class Method
public function getStatus($record_id){
$query = " SELECT `status` from records ";
$query.= " WHERE `record_id`='{$record_id}' ";
/* Get query response */
$response = $this->QueryKey($query);
if($response==true){
$output['success']=$response[0];
}
return json_encode($response);
}
Thank you!
Simply, You call ajax code in every 5 sec duration and get the status...
function checkStatusRealTime(){
$.ajax({
type:'get',
url:getStatus.php?record_id=50,
success: function(e){
if(status == 'pending'){
// code...
}else if(status == 'success'){
clearInterval(realTimeCheck);
}else{
}
}
});
}
let realTimeCheck = setInterval(checkStatusRealTime,5000); //call every 5sec

Try to pass 2 variables to php using ajax jquery

I've been looking to find a way to update some data into my database when execute onclick function.
The idea is to update the value of a button contains the word "Active" and when execute onclick like to update into mysql to "Inactive"
This is the button:
$register_status = '<button class="btn btn-success btn_status btn-block" data-status="Active">Active</button>';
How to give the data variable so that we can fetch it in PHP using $_POST? The above representation of the data variable shows an error.
scripts.js
$(document).ready(function(){
$('body').click('.btn_status', function(e){
var button = jQuery(e.target);
if(button.data('status') == 'Active'){
var data = {id:id, register_status:Inactive};
$.ajax({
type: "POST",
dataType: "json",
url: "ajax/updateStatus.php",
data: data,
success: function(data) {
alert("update!");
}
});
}else if(button.data('status') == 'Inactive'){
alert("nothing");
}
});
})
ajax/updateStatus.php
include("db_connection.php");
if(isset($_POST))
{
$id = $_POST['id'];
$register_status = $_POST['register_status'];
$query = "UPDATE `users` SET `register_status` = '$register_status' WHERE `id` = '$id'";
if (!$result = mysqli_query($db,$query)) {
exit(mysqli_error());
}
}
UPDATE:
This is another function to delete. This function is run correctly.
function DeleteUser(id) {
$.post("ajax/deleteUser.php", {
id: id
},
function (data, status) {
readRecords();
}
);
}
deleteUser.php
<?php
if(isset($_POST['id']) && isset($_POST['id']) != "")
{
include("db_connection.php");
$user_id = $_POST['id'];
$query = "DELETE FROM users WHERE id = '$user_id'";
if (!$result = mysqli_query($db,$query)) {
exit(mysqli_error());
}
}
?>
and when do a click I can remove:
<li onclick="DeleteUser('.$row['id'].')">Delete</li>
However, this doesn't seem to work. If there's a better way to do what I mentioned above. thanks
Based on the example, you will want to make some changes:
JavaScript
$(function(){
function updateStatus(id, st){
$.post("ajax/updateStatus.php", {"id": id, "register_status": st}, function(data, status){
console.log("Update Success", data, status);
readRecords();
});
}
$('body').on('click', '.btn_status', function(e){
var button = $(this);
updateStatus(1001, (button.data("status") === "Active" ? "Inactive" : "Active"));
});
});
First, using the click() as you had, was not exactly the best way to do it. Using .on() will be better as it can handle any new or dynamically created items.
This script will require id to be defined someplace. The AJAX needs to send the id info to the PHP. The code you posted does not show this, so I am not sure what it's value should be.
PHP (updateStatus.php)
include("db_connection.php");
if(isset($_POST['id'])){
$id = (int)$_POST['id'];
$register_status = ($_POST['register_status'] == "Inactive" ? "Inactive" : "Active");
$query = "UPDATE `users` SET `register_status` = '$register_status' WHERE `id` = '$id'";
if (!$result = mysqli_query($db,$query)) {
exit(mysqli_error());
}
}
These updates can help prevent SQL Injection. I would advise using Prepared Statements to further prevent it.
Update
If you're button is going to be something like this:
<button onclick="ChangeStatus('.$row['id'].') class="btn btn-success btn_status btn-block" data-status="Active">Active</button>
Notice that this is only passing in just the ID from PHP. If these items will always be "Active", then yes, you can do this with something like:
function ChangeStatus(id){
$.post("ajax/updateStatus.php", {id: id}, function(data, status){ console.log(status, data)});
}
With PHP like:
<?php
if(isset($_POST['id']) && $_POST['id'] != ""){
include("db_connection.php");
$user_id = (INT)$_POST['id'];
$query = "UPDATE `users` SET `register_status` = 'Inactive' WHERE `id` = '$user_id'";
if (!$result = mysqli_query($db,$query)) {
exit(mysqli_error());
}
}
?>
Hope this helps.

Retrieving data from ajax in php

I have a simple ajax call firing on click of a button, sending the element's id attribute via POST, No errors and the data is being sent, I checked on the network console.
Therefore the next logical step is to think it's an issue with the php, in which i'm making a simple update statement, the issue is the php can't see the data passed by the ajax call. please see below:
AJAX:
$("a.report_btn").click(function() {
var url = "report_post.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("a.report_btn").attr("id"),
success: function(response) {
content.html(response);
$(".liked_success").show();
}, error:function(exception){alert('Exeption:'+exception);}
});
return false; // avoid to execute the actual submit of the form.
});
PHP:
<?php include 'db_connect.php';
$id =$_POST['id'];
try {
$sql = "UPDATE jobs_list
SET post_like = post_like+1, TimeStamp = TimeStamp
WHERE id=$id
LIMIT 1";
$statement = $dbh->prepare($sql);
$statement->bindValue("id", $id, PDO::PARAM_INT);
$statement->bindValue("post_like", $_POST['post_like'], PDO::PARAM_INT);
$count = $statement->execute();
$dbh = null; // Disconnect
}catch( PDOException $e ) {
echo 'Ops... something went wrong...'; // error message
var_dump($statement);
}
?>

JQuery Ajax Updating MySQL Database, But Not Running Success Function

I am currently using the JQuery ajax function to call an exterior PHP file, in which I select and add data in a database. Once this is done, I run a success function in JavaScript. What's weird is that the database is updating successfully when ajax is called, however the success function is not running. Here is my code:
<!DOCTYPE html>
<head>
<script type="text/javascript" src="jquery-1.6.4.js"></script>
</head>
<body>
<div onclick="addtask();" style="width:400px; height:200px; background:#000000;"></div>
<script>
function addtask() {
var tid = (Math.floor(Math.random() * 3)) + 1;
var tsk = (Math.floor(Math.random() * 10)) + 1;
if(tsk !== 1) {
$.ajax({
type: "POST",
url: "taskcheck.php",
dataType: "json",
data: {taskid:tid},
success: function(task) {alert(task.name);}
});
}
}
</script>
</body>
</html>
And the PHP file:
session_start();
$connect = mysql_connect('x', 'x', 'x') or die('Not Connecting');
mysql_select_db('x') or die ('No Database Selected');
$task = $_REQUEST['taskid'];
$uid = $_SESSION['user_id'];
$q = "SELECT task_id, taskname FROM tasks WHERE task_id=" .$task. " LIMIT 1";
$gettask = mysql_fetch_assoc(mysql_query($q));
$q = "INSERT INTO user_tasks (ut_id, user_id, task_id, taskstatus, taskactive) VALUES (null, " .$uid. ", '{$gettask['task_id']}', 0, 1)";
$puttask = mysql_fetch_assoc(mysql_query($q));
$json = array(
"name" => $gettask['taskname']
);
$output = json_encode($json);
echo $output;
Let me know if you have any questions or comments, thanks.
Ibelieve it runs but alert wont show because of error -
success: function(task) {alert(task.name);}
You have to decode JSON first with jQuery.parseJSON(), task is just a string
it shoudld look somthing like this
function(m)
{
var task = jQuery.parseJSON( m );
alert(task['name']);
}
Edit:
Ok ...
Try to use developer tools in your browser and place breakpoint on your success function, if it doesnt even lunch try to add error callback for your ajax call
error: function(xhr, exc)
{
alert(xhr.status);
alert(exc);
}
Edit2:
and there is your problem - your ajax is not only returning json data, but php warning too, and now I see where is your problem - you are fetching data after insert, delete
$puttask = mysql_fetch_assoc(mysql_query($q));
Now I feel bad for not noticing it sooner...

How does Ajax work with PHP?

I'm having troubles using ajax and php. What I'm trying to do is call an ajax function that grabs a value from an form's input, and checks if that email exists in a database. Here is my current javascript:
//Checks for Existing Email
function checkExisting_email() {
$.ajax({
type: 'POST',
url: 'checkExist.php',
data: input
});
emailExists = checkExisting_email();
//If it exists
if (emailExists) {
alert("This email already exists!");
}
Unfortunately, I can't get my alert to go off. In my PHP function, it checks whether the input is a username or an email (just for my purposes, and so you know), and then it looks for it in either column. If it finds it, it returns true, and if not, it returns false:
include ('func_lib.php');
connect();
check($_POST['input']);
function check($args)
{
$checkemail = "/^[a-z0-9]+([_\\.-][a-z0-9]+)*#([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i";
if (!preg_match($checkemail, $args)) {
//logic for username argument
$sql = "SELECT * FROM `users` WHERE `username`='" . $args . "'";
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res) > 0) {
return true;
} else {
return false;
}
} else {
//logic for email argument
$sql = "SELECT * FROM `users` WHERE `email`='" . $args . "'";
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res) > 0) {
return true;
} else {
return false;
}
}
}
SO my issue is, how does ajax respond to these returns, and how do I make ajax function accordingly? Mainly, why doesn't this work?
Any help is very much appreciated. Thank you!
You need to add the success option to your Ajax request, which is the JS function which gets executed when the XHR succeeds. Have a look at the jQuery documentation for more info.
Without running the script, I think you'll find that $_POST['input'] is empty; you need to pass your data as something like data: {'input': input} to do that.
Your PHP also needs to return some content to the script; consider changing your call to check() to something like this:
echo (check($_POST) ? 'true' : 'false');
You can now check the content in JavaScript.
Basically ajax is a hand-shaking routine with your server.
Ajax:
$.post('yoursite.com/pagewithfunction.php',
{postkey1:postvalue1, postkey2:postvalue2...},
function (response) {
// response is the data echo'd by your server
}, 'json'
);
pagewithfunction:
yourFunction(){
$var1 = $_POST['postkey1'];....
$result = dosomething($var1..);
echo json_encode($result); // this is passed into your function(response) of ajax call
}
So in $.post you have the url of the php page with the function, { var:val } is the post data, and function(response) is where you handle the data that is echo'd from your server -- the variable, response, is the content that is echo'd.

Categories