Try to pass 2 variables to php using ajax jquery - php

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.

Related

php function returning value for some pages, but fails to return values for other pages with same document structure

So here I want to get an ID for the specific user, using a php page, and then perform database insert using a function defined in a file named 'functions.php'. So basically, I am capturing values from a page using jQuery ajax() method and sending the data to a php page named 'follow_school.php'. The rest of what's happening would be clear from the code, I provide below:
jQuery code:
jQuery(document).ready(function() {
var school_name = jQuery('#school-name').text();
var session_var = jQuery('#session').text();
// console.log(session_var);
var button_text_onload =
localStorage.getItem("btnText_"+school_name+"_for_"+session_var);
console.log(button_text_onload);
if (button_text_onload !== null) {
jQuery('#follow-button').html(button_text_onload);
} else {
jQuery('#follow-button').html('Follow');
}
jQuery('#follow-button').click(function() {
// alert (session_var);
// console.log(session_var);
var button_text = jQuery('#follow-button').text();
// alert(button_text);
if (button_text === 'Follow') {
jQuery.ajax({
type: 'POST',
url:
'https://mim-insider.com/wp-content/themes/Divi/follow_school.php',
data: {name : school_name,
email : session_var
},
success: function(result) {
console.log(result);
var key = "btnText_" + school_name +"_for_" +
session_var;
console.log(key);
localStorage.setItem(key, "Unfollow");
jQuery('#follow-button').html('Unfollow');
}});
} else {
jQuery.ajax({
type: 'POST',
url:
'https://mim-insider.com/wp-content/themes/Divi/unfollow_school.php',
data: {name : school_name,
email : session_var,
},
success: function(result) {
console.log(result);
var key = "btnText_" + school_name +"_for_" +
session_var;
console.log(key);
localStorage.setItem(key, "Follow");
jQuery('#follow-button').html("Follow");
}});
}
});
});
follow_school.php
<?php
include_once "includes/db.php";
include_once "includes/functions.php";
$name = $_POST['name'];
$email = $_POST['email'];
$id = get_id($email);
/* for debugging purpose */
if ($id == null) {
var_dump($id);
} else {
echo $id;
}
echo $email;
/* insert operation */
insert_school($id, $name);
?>
functions.php
function get_id($email) {
global $conn;
$sql = "SELECT id FROM member WHERE email = '$email'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
return $row["id"];
}
function insert_school($id, $name) {
global $conn;
$sql = "INSERT INTO user_schools (user_id, school_name)
VALUES ('$id', '$name')";
$conn->query($sql);
}
NOTE: Here the database connection is perfectly fine, and these codes worked for some pages earlier. But apparently, other pages don't seem to run the code, or to be precise, returns "null" as id. Also, I would like to mention that, the table entries and fields are not null, or unspecified. They are perfectly fine, as I said, it worked for some pages.
Please can anyone guide me, as to what's going wrong here, because after dedicating so much of my time on this, i still am not able to understand the issue.
Thank you.

Ajax - Check for database update

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'];

Updated values are not being added to server database using ajax? [duplicate]

This question already exists:
Database values are not updating?
Closed 8 years ago.
I am using this code to call ajaxvote.php
$('.vote').click(function(){
$.ajax({
url: 'ajaxvote.php',
type: 'POST',
cache: 'false',
success: function () { alert("Success!"); } ,
error: function () { alert("Error!"); }});
var self = $(this);
var action = self.data('action');
var parent = self.parent().parent();
var postid = parent.data('postid');
var score = parent.data('score');
if (!parent.hasClass('.disabled')) {
if (action == 'up') {
parent.find('.vote-score').html(++score).css({'color':'orange'});
self.css({'color':'orange'});
$.ajax({data: {'postid' : postid, 'action' : 'up'}});
}
else if (action == 'down'){
parent.find('.vote-score').html(--score).css({'color':'red'});
self.css({'color':'red'});
$.ajax({data: {'postid' : postid, 'action' : 'down'}});
};
parent.addClass('.disabled');
This is the code from my webpage
<div class="item" data-postid="<?php echo $rows['ID'] ?>" data-score="<?php echo $rows['VOTE'] ?>">
<div class="vote-span">
<div class="vote" data-action="up" title="Vote up"><i class="fa fa-camera-retro"></i></div>
<div class="vote-score"><?php echo $rows['VOTE'] ?></div>
<div class="vote" data-action="down" title="Vote down"><i class="fa fa-camera-retro"></i></div>
</div>
This is my php code
if ($_SERVER['HTTP_X_REQUESTED_WITH']) {
if (isset($_POST['postid']) && (isset($_POST['action']))) {
$postId = $_POST['postid'];
if (isset($_SESSION['vote'][$postId])) return;
$query = $mysqli - > query("SELECT VOTE from stories WHERE ID = $postId LIMIT 1");
while ($rows = mysqli_fetch_array($query)) {
if ($_POST['action'] === 'up') {
$vote = ++$rows['VOTE'];
} else {
$vote = --$rows['VOTE'];
}
$mysqli - > query("UPDATE stories SET VOTE = $vote WHERE ID = $postId ");
$_SESSION['vote'][$postId] = true;
}
}
}
I know I can connect to database because I can login. I also get the alert success I have set up above, However, the values are not updating in Database.
EDIT
I have added more Ajax code that I had already written.
When posting via ajax, you need to send through the data you actually want to post.
var postData = {name:"Mister",lastName:"Frodo"}; //Array
$.ajax({
url : "ajaxvote.php",
type: "POST",
data : postData,
success: function(data, textStatus, jqXHR)
{
//Handle response
},
error: function (e) {
// Handle error
}
});
In this case, the post ID and score needs to be grabbed. You also need to grab what kind of action is clicked (typically through a click event bind on the divs with class="vote". For example purposes, let's just set it to "up" for now:
var postId = $('div.item').attr('data-postid').val();
var score = $('div.item').attr('data-score').val();
var postData = {postId: postId, score: score, action: 'up'}
You can now post that "postData" to your ajaxvote.php.
Also, you can use jQuery's $.POST method
$.post("ajaxvote.php", { name: "Mister", lastName: "Frodo" } );
Now for parsing your form, have a look at jQuery's serialize which goes through your form takes each input's [name] attribute along with the value to create a data-string.
Example
name=Mister&lastName=Frodo
This is ideal for sending through with the "data" attribute in $.ajax. Have a look at this answer for more regarding jQuery's serialize.

mysql query loading forever in codeigniter php

I have no idea why the below is not working. I have tested mysql on an alternative project, and it works.
Maybe you guys can see what I am not: The User clicks the submit button:
HTML:
<form class='find_form'>
<input class='find_value'/>
<input class="find_submit" type="submit"/>
</form>
JS:
$(".find_submit").click(function() {;
var value = $('.find_value').val();
if (value == false) { return false; } else {
var request = $.ajax({
type: "POST",
url: "/forum/index.php/ajax/find_active",
dataType: 'json',
data: {value: value}
});
request.done(function (response){
console.log(response);
//update history
//update threads
//update activecontent['thread_name']
active(response['active']);
});
return false;
}
});
AJAX/find_active:
function find_active()
{
$active = $this->input->post('value');
$active_list = $this->search_model->find_active($active);
//...//
}
search_model:
public function find_active($active)
{
$sql = "SELECT *
FROM keywords
WHERE keywords.keyword
LIKE '%$active%'
ORDER BY count DESC";
$query = $this->db->query($sql);
return $query->result_array();
}
After hitting submit, it runs ajax/find_active and in firebug, the wheel keeps turning until I get a memory error.
I have reverted back to a working revision, and added ONLY the query. So I am 99% sure its whats causing the problem.
Any ideas?

AJAX request(delete a comment)

I'm trying to delete a mysql record with javascript but I fail.
So this is my js function
function delpost(id){
if(confirm('Are you sure?')){
$('#comment_'+id).hide();
http.open("get","/index.php?p=delcomment&id=" + id, true);
http.send();
}
}
And this is my delcomment.php(included through index.php)
$comment_id = $_GET['id'];
if(logged() && $status=="administrator"){
$delquery = mysql_query("DELETE FROM comments WHERE id='$comment_id' LIMIT 1");
die();
}else{
die();
}
I hope you can help me with this :)
update:
try using
http.send(null)
instead of
http.send()
also, use firebug to see if your ajax request is actually being sent to the server
better solution:
(php rusty!)
delcomment.php
$comment_id = $_POST['id'];
$comment_id = mysql_real_escape_string($comment_id);
if(logged() && $status=="administrator"){
$query = "DELETE FROM comments WHERE id='{$comment_id}'";
$result = mysql_query($query, $con);
die();
}else{
die();
}
using jquery to post (make sure to include the jquery.js), your javascript function should be like this:
function delpost(id){
if(confirm('Are you sure?')){
$.ajax({
type: "POST",
url: "/index.php",
data: {p: "delcomment", id: id},
success: function(){
$('#comment_'+id).hide();
},
error: function(){
alert('failure');
}
});
}
}

Categories