Updating database with an AJAX call using a particular id - php

I am attempting to do my first AJAX call and what I am trying to do is pretty simple, but my db is not being updated.
All I am trying to do is when I hit the accept button next to a user, for their id to be taken and sent with the new status 'Accepted' and for the status to change from 'Pending' to 'Accepted' for that particular user in my user_requests db table.
Nothing is being changed in the db and the only thing that is happening with the AJAX code is I get my #success message, but for maybe 0.3 of a second and it does not fade out.
Does anyone see what I am doing wrong in my attempt?
<h2>Pending User Requests</h2>
<br />
<div id="success" style="color: red;"></div>
<?php
$con = mysqli_connect("localhost", "root", "", "db");
$run = mysqli_query($con,"SELECT * FROM user_requests ORDER BY id DESC");
$numrows = mysqli_num_rows($run);
if( $numrows ) {
while($row = mysqli_fetch_assoc($run)){
//comment added by php-dev : condition could be set in the query -->
if($row['status'] == "Pending"){
$pending_id = $row['id'];
$pending_user_id = $row['user_id'];
$pending_firstname = $row['firstname'];
$pending_lastname = $row['lastname'];
$pending_username = $row['username'];
?>
<!-- comment added by php-dev : useless form tag -->
<form action="" method="POST" id="status">
<!-- comment added by php-dev : useless input field, no field name -->
<input type='hidden' value='<?php echo $pending_id; ?>' id='pending_id' />
<?php
// comment added by php-dev : comparing string to boolean value true
if ($pending_firstname == true) {
echo "Name - ". $pending_firstname . " " . $pending_lastname . "</br>"
. "Username - ". $pending_username . "</br></br>"
?>
<!-- comment added by php-dev : conditional form closing tag -->
</form>
<button class="approve" type="submit" form="status" name="approve"
value="<?= $pending_id; ?>">
Approve
</button>
<button id="deny" type="submit" form="status" name="deny" value="Denied">
Deny
</button>
<br><br><br>
<?php
// comment added by php-dev : else statement misplaced -->
;} else {
echo "There are no Pending Requests at this time.";
}
}
}
}
?>
My AJAX call...
<script>
$(document).ready(function(){
$('.approve').click(function(){
$.ajax({
url: 'userRequest_approve.php',
data: {
id: $(this).val(), //the value of what you clicked on
//you clicked on it so you know the status might as well hardcode it
status: 'Approved'
},
success: function(data) {
//do something with the data that got returned
// comment added by php-dev : for debug purposes, the #success should show
// the server reponse instead
$('#success').html('User Status Changed!');
//do something with the data that got returned
$('#success').delay(5000).fadeOut(400);
},
type: 'POST'
});
});
});
</script>
My userRequest_approve.php file to insert into db to update the status...
<?php
require_once 'core/init.php';
$term = mysql_escape_string($term); // Attack Prevention
$pending_id = $_POST['id'];
$status = $_POST['approve'];
$con = mysqli_connect("localhost","root","","db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $con->prepare(
"INSERT INTO user_requests (status, date_responded) VALUES (?, NOW())"
);
if ( false===$stmt ) {
// Check Errors for prepare
die('User Request update prepare() failed: ' . htmlspecialchars($con->error));
}
$stmt->bind_param('s', $status);
// comment added by php-dev : should be false === $stmt->bind_param ...
if ( false===$stmt ) {
// Check errors for binding parameters
die('User Request update bind_param() failed: ' . htmlspecialchars($stmt->error));
}
$stmt->execute();
// comment added by php-dev : should be false === $stmt->execute ...
if ( false===$stmt ) {
die('User Status update execute() failed: ' . htmlspecialchars($stmt->error));
}
?>

If you want to update, you should try this:
$stmt = $con->prepare("UPDATE user_requests SET status=?, date_responded=NOW() WHERE id=?");
$stmt->bind_param('si', $status, $pending_id);
You also need a name attribute on your hidden so it'll be sent:
<input type='hidden' name='id' value='<?php echo $pending_id; ?>' id='pending_id'/>
Original Answer
I only see one issue:
This is the ajax request you're using:
$.ajax({
url: 'userRequest_approve.php',
data: {
id: $(this).val(), //<< id
status: 'Approved' //<< status
},
success: function(data) {
//do something with the data that got returned
$('#success').html('User Status Changed!');
$('#success').delay(5000).fadeOut(400);//do something with the data that got returned
},
type: 'POST'
});
Note that the data you're sending is id and status.
However, on the PHP side:
$pending_id = $_POST['id']; //yep
$status = $_POST['approve']; //does it exist?
You should be using
$status = $_POST['status'];

Related

ajax to submit php form to database, ajax part doesn't work

I'm very new to ajax so I followed a tutorial but I can't get it to work. I tried search this forum for an answer but with no luck..
HTML (a bit stripped down from classes and bootstrap-stuff)
<form id="editUserForm" role="form">
<input id="edit_employeenr" type="text" name="employeenr">
<input id="edit_name" type="text" name="name">
<select id="edit_membertype" name="membertype">
<option value="1">Admin</option>
<option value="2">Employee</option>
</select>
<input type="submit" value="Save">
</form>
<div id="editUserMsg">Successfully updated!</div>
JS
$(document).ready(function() {
$("#editUserMsg").hide();
$("#editUserForm").submit(function(event) {
event.preventDefault();
submitUserEdit();
});
function submitUserEdit(){
var dataString = $("#editUserForm").serialize();
$.ajax({
type: "POST",
url: "user_edit_process.php",
data: dataString,
success: function(text){
if (text == "success"){
userEditSuccess();
}
}
});
}
function userEditSuccess(){
$("#editUserMsg").show().delay(5000).fadeOut();
}
});
PHP (user_edit_process.php)
<?php
$employeenr = $_POST['employeenr'];
$name = $_POST['name'];
$membertype = $_POST['membertype'];
$stmt = $link->prepare("UPDATE users SET employeenr = ?, name = ?, membertype = ?");
$stmt->bind_param("isi", $employeenr, $name, $membertype);
$stmt->execute();
if ($stmt) {
echo 'success';
} else {
echo 'fail';
}
?>
if i put the $("#editUserMsg").show().dealy(5000).fadeOut(); just above the $.ajax the message appears, so that must mean that the ajax code isn't working correct. Any suggestions?
EDIT Solved. I had forgotten to include the file where the variable $link wes defined.
It seems that you have a problem in your either in your prepare statement or in the bind_parameter. You should always check for error, so I suggest you do like this to check for errors:
<?php
$employeenr = $_POST['employeenr'];
$name = $_POST['name'];
$membertype = $_POST['membertype'];
if (!($stmt = $mysqli->prepare("UPDATE users SET employeenr = ?, name = ?, membertype = ?"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if (! $stmt->bind_param("isi", $employeenr, $name, $membertype)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
?>
and then in you JS, add this to your success method:
console.log(text);
Check your Firefox console (Ctrl-Shift-Q), and if there is an error you would find it under "Network" -> Click the "user_edit_process.php" in the list -> and in the right window under "Preview".
Is that all code that you have in user_edit_process.php?
Is the $link variable properly initialize?
You can try to comment part of your code in PHP file, and write something like below to test if you Ajax code work properly:
<?php
$employeenr = $_POST['employeenr'];
$name = $_POST['name'];
$membertype = $_POST['membertype'];
// $stmt = $link->prepare("UPDATE users SET employeenr = ?, name = ?, membertype = ?");
// $stmt->bind_param("isi", $employeenr, $name, $membertype);
// $stmt->execute();
if ($employeenr) {
echo 'success';
} else {
echo 'fail';
}
And then if you type something in first employeenr form input it should show Successfully updated!. If you leave this input empty and send form, it shouldn't show.

Insert data into mysql database with php and ajax in wordpress

inside my function.php I added new top level admin menu. I added input fields and inside it and put it into html form element.
<form id="prices_form" method="post" action="">
<div style=font-weight:bold;font-size:16px;>Location 1</div>
<input id="location1" name="location1" type="text" />
<input type="hidden" name="count" value="1" />
<div style=font-weight:bold;font-size:16px;>Location 2</div>
<input class="input" id="location2" name="location2" type="text" placeholder="Type something"/>
<div style=font-weight:bold;font-size:16px;>Price(KN)</div>
<input type="number" id="price" name="price" min="0" step="0.01"/><br>
<input id="submit" name="submit" type="submit" value="Save prices" />
</form>
Then I added php where I call ajax via ajax-admin.php and gives user possibility to use ajax. So I want to add input fields into database on submit click.
function ajax_savePrice(){
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$location1 = $_POST['location1'];
$location2 = $_POST['location2'];
$price = $_POST['price'];
$result = $conn->query("SELECT * FROM prices WHERE location1 = '$location1' AND location2='$location2' OR location1 = '$location2' AND location2='$location1'");
$row_count = $result->num_rows;
if ($row_count >= 1) {
echo 'That locations are already inserted. Do you want to update price?';
} else {
$query = "INSERT INTO prices (location1, location2, price) VALUES(?, ?, ?)";
$statement = $conn->prepare($query);
//bind parameters for markers, where (s = string, i = integer, d = double, b = blob)
$statement->bind_param('ssi', $location1, $location2, $price);
if ($statement->execute()) {
print 'Success! ID of last inserted record is : ' . $statement->insert_id . '<br />';
} else {
die('Error : (' . $conn->errno . ') ' . $conn->error);
}
$statement->close();
}
}
function ajax_savePrice_init(){
wp_register_script('ajax-savePrice-script', get_template_directory_uri() . '/ajax-savePrice-script.js', array('jquery') );
wp_enqueue_script('ajax-savePrice-script');
wp_localize_script( 'ajax-savePrice-script', 'ajax_savePrice_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'redirecturl' => home_url(),
'loadingmessage' => __('Sending data, please wait...')
));
// Enable the user with no privileges to run ajax_login() in AJAX
add_action( 'wp_ajax_nopriv_ajaxsavePrice', 'ajaxsavePrice' );
add_action( 'wp_ajax_ajaxsavePrice', 'ajaxsavePrice' );
}
add_action('init', 'ajax_savePrice_init');
And I made .js file to proccess ajax request:
jQuery(document).ready(function($) {
// Perform AJAX login on form submit
$('#prices_form').on('submit', function(e){
$.ajax({
type: 'POST',
dataType: 'json',
url: ajax_savePrice_object.ajaxurl,
data: {
'action': 'ajaxsavePrice',
'location1': $('#location1').val(),
'location2': $('#location2').val(),
'price': $('#price').val() },
success: function(data){
$('#prices_form').hide();
}
});
e.preventDefault();
});
});
Page reloads and nothing happens...
Any hint?
EDIT:
I succeed to call ajax and added 3 echo-s to my php so I can get response via server.
$result = $conn->query("SELECT * FROM prices WHERE location1 = '$location1' AND location2='$location2' OR location1 = '$location2' AND location2='$location1'");
$row_count = $result->num_rows;
if ($row_count >= 1) {
// echo 'That locations are already inserted. Do you want to update price?';
echo 'exist';
} else {
$query = "INSERT INTO prices (location1, location2, price) VALUES(?, ?, ?)";
$statement = $conn->prepare($query);
//bind parameters for markers, where (s = string, i = integer, d = double, b = blob)
$statement->bind_param('ssi', $location1, $location2, $price);
if ($statement->execute()) {
// print 'Success! ID of last inserted record is : ' . $statement->insert_id . '<br />';
echo 'yes';
} else {
//die('Error : (' . $conn->errno . ') ' . $conn->error);
echo 'no';
}
$statement->close();
}
Now in my js:
location1=$("#location1").val();
location2=$("#location2").val();
price=$("#price").val();
data: "location1="+location1+"location2="+location2+"price="+price,
success: function(html){
if(html==='exist')
{
$("#prices_form").fadeOut("normal");
}
else
{
$("#aaa").fadeOut("normal");
}
},
beforeSend:function()
{
}
});
return false;
});
So whatever I enter in my input fields and post to php I got this else part. I tried with all 3 states that php can return to js but always else get executed.
Any hint now?
Name your form in html as -
<form id="prices_form" name="pricesForm" method="post" action="">
Try JSON.stringify() data before sending with the AJAX like below -
var data = JSON.stringify({
action: 'ajaxsavePrice',
location1: $('#location1').val(),
location2: $('#location2').val(),
price: $('#price').val()
});
And then replace your ajax call on form submit as below-
$('form.pricesForm').on('submit', function(e){
e.preventDefault();
$.ajax({
method: 'POST',
dataType: 'json',
url: ajax_savePrice_object.ajaxurl, // also check this if it returns the correct url
data: data,
success: function(res){
$('#prices_form').hide();
}
});
});
Hope this helps.

PHP and MySQLi query always returning 0

The following code seems to be not working correctly. I'm new to PHP and jQuery.
php:
<?php
//if (!defined('BOOTSTRAP')) { die('Access denied'); }
//if we got something through $_POST
if (isset($_POST['postcode_locator_search'])) {
// here you would normally include some database connection
//include('config.local.php');
//Open a new connection to the MySQL server
$mysqli = new mysqli('localhost','test','c#W)ukmd[0bm','test');
//Output any connection error
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
// never trust what user wrote! We must ALWAYS sanitize user input
$postcode_q = mysqli_real_escape_string($mysqli, $_POST['postcode_locator_search']);
$postcode_q = htmlentities($postcode_q);
// A select query. $result will be a `mysqli_result` object if successful
$result = mysqli_query("SELECT description FROM cscart_postcode_location_descriptions WHERE cscart_postcode_location_descriptions LIKE '%" . $postcode_q . "%' ORDER BY cscart_postcode_location_descriptions LIMIT 1");
if($result === false) {
// Handle failure - log the error, notify administrator, etc.
echo '1';
} else {
// Fetch all the rows in an array
echo '0';
}
$mysqli->close();
}
?>
JS / HTML:
{assign var="prod_id" value=$product.product_id}
<form action="search_postcode.php" method="post" class="postcode_locator_form" name="postcode_locator_form">
<div class="ty-control-group">
<label for="postcode_locator_search{$block.block_id}" class="ty-control-group__title">{__("postcode_search")}</label>
<p class="filling-notice">{__("postcode_search_desc")}</p>
<div class="ty-input-append ty-m-none">
<input type="text" size="20" class="ty-input-text" id="postcode_locator_search" name="postcode_locator_search" value="{$postcode_locator_search.q}" />
{include file="buttons/go.tpl" but_name="postcode_locator.search" alt=__("search")}
</div>
</div>
</form>
<div class="filling-status filling-success">
<h3>Add filling to your bean bag</h3>
<p>Searched postcode: <span class="searched-postcode"></span></p>
<p class="beans-msg">{__("add_some_beans_success")} {__("click_here")}</p>
</div>
<div class="filling-status filling-failure">
<h3>Add filling to your bean bag</h3>
<p>Searched postcode: <span class="searched-postcode"></span></p>
<p class="beans-msg">{__("add_some_beans_error")}</p>
</div>
<script>
$(function() {
$(".filling-status").hide();
$(".postcode_locator_form .ty-btn-go").click(function() {
// getting the value that user typed
var searchString = $("#postcode_locator_search").val();
// forming the queryString
var data = 'postcode_locator_search='+ searchString;
// if searchString is not empty
if(searchString) {
// ajax call
$.ajax({
type: "POST",
url: "search_postcode.php",
data: data,
beforeSend: function(html) { // this happens before actual call
$(".searched-postcode").html(searchString);
},
success: function(data){ // this happens after we get results
console.log(data);
if(data == '0'){
$(".filling-status.filling-success").show();
} else if(data == '1'){
$(".filling-status.filling-failure").show();
}
}
});
}
return false;
});
});
</script>
The communication is all working, but it always returns 0 as a success from whatever I search for and seems to not check database for the result.
What I need is if I search something and it's a match, to return 0 as a success but if not found / a match to return 1 as a failure.
If you want to retrieve your data:
$result = mysqli_query("SELECT description FROMcscart_postcode_location_descriptions WHERE cscart_postcode_location_descriptions LIKE '%" . $postcode_q . "%' ORDER BY cscart_postcode_location_descriptions LIMIT 1");
if($result === false) {
// Handle failure - log the error, notify administrator, etc.
echo '1';
} else {
// Fetch all the rows in an array
while($row = mysqli_fetch_assoc($result)){
echo $row['id']; //prints the resulted id
}
}
Use mysqli_num_rows to detect if you have a result
if($result === false or mysqli_num_rows($result) === 0) {
echo '1';
}
I would recommend breaking this into two if conditions though so that you handle errors separately from a query with no result

Getting 0 as a value sending to my database during an AJAX call form submission

I am trying to send the user id and the value 'Approved' through the AJAX call to my prepared statement to send into my database. As of right now I am getting the id part of this correctly. However, the value for the Approved part is sending and updating my database as a 0.
Does anyone see why?
My Form
$con = mysqli_connect("localhost", "root", "", "db");
$run = mysqli_query($con,"SELECT * FROM user_requests ORDER BY id DESC");
$numrows = mysqli_num_rows($run);
if( $numrows ) {
while($row = mysqli_fetch_assoc($run)){
if($row['status'] == "Pending"){
$pending_id = $row['id'];
$pending_user_id = $row['user_id'];
$pending_firstname = $row['firstname'];
$pending_lastname = $row['lastname'];
$pending_username = $row['username'];
?>
<form action="" method="POST" id="status">
<input type='hidden' name='id' value='<?php echo $pending_id; ?>' id='pending_id'/>
<?php
if ($pending_firstname == true) {
echo "Name - ". $pending_firstname . " " . $pending_lastname . "</br>" .
"Username - ". $pending_username . "</br></br>"
//echo print_r($_POST);
?>
<button class="approve" type="submit" form="status" name="approve" value="<?=$pending_id;?>">Approve</button>
<button class="deny" type="submit" form="status" name="deny" value="<?=$pending_id;?>">Deny</button>
</form><br><br><br>
My AJAX call
$(document).ready(function () {
$('.approve').click(function () {
$.ajax({
url: 'userRequest_approve.php',
type: 'POST',
data: {
id: $(this).val(), //id
status: 'Approved' //status
},
success: function (data) {
//do something with the data that got returned
$("#success").fadeIn();
$("#success").show();
$('#success').html('User Status Changed!');
$('#success').delay(5000).fadeOut(400);
},
//type: 'POST'
});
return false;
});
});
My Prepared Statement
$pending_id = $_POST['id'];
$status = $_POST['status'];
$con = mysqli_connect("localhost", "root", "", "db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $con->prepare("UPDATE user_requests SET status=?, date_responded=NOW() WHERE id=?");
if ( false===$stmt ) {
// Check Errors for prepare
die('User Request update prepare() failed: ' . htmlspecialchars($con->error));
}
$stmt->bind_param('ii', $status, $pending_id);
// comment added by php-dev : should be false === $stmt->bind_param ...
if ( false===$stmt ) {
// Check errors for binding parameters
die('User Request update bind_param() failed: ' . htmlspecialchars($stmt->error));
}
$stmt->execute();
// comment added by php-dev : should be false === $stmt->execute ...
if ( false===$stmt ) {
die('User Status update execute() failed: ' . htmlspecialchars($stmt->error));
}
By ajax form you are providing "status" as string with value "Approved" to server while you are assuming it integer in binding. Just change "status" in ajax code to '1'
Based on the other answer it clicked what I was doing wrong. I had my php parameters set as both being integer when it needed to be 'si' not 'ii'.

Sending AJAX call to a php file to INSERT a value into my database

I I have a db table called user_requests where I have a column called 'status'. I output the status' on the page userRequests.php. I output all of the user requests via while loops. What I am trying to accomplish is being able to hit the button 'approve' or 'deny' to change the 'status' in my user_requests table. I am trying to do this with AJAX and this is my first attempt at making an AJAX call. When I click on approve I want it to grab the id of the user I selected Accept next to and then carry the value of 'Accept' and INSERTthat into my user_requests db table in the 'status' row.
As I have it now nothing happens at all. Does anyone see anything wrong with how how I am trying to do this?
userRequests.php
<?php
$con = mysqli_connect("localhost", "root", "", "db");
$run = mysqli_query($con,"SELECT * FROM user_requests ORDER BY id DESC");
$numrows = mysqli_num_rows($run);
if( $numrows ) {
while($row = mysqli_fetch_assoc($run)){
if($row['status'] == "Pending"){
$pending_id = $row['id'];
$pending_user_id = $row['user_id'];
$pending_firstname = $row['firstname'];
$pending_lastname = $row['lastname'];
$pending_username = $row['username'];
?>
<form action="" method="POST" id="status">
<input type='hidden' value='<?php echo $pending_id; ?>' id='pending_id'/>
<?php
if ($pending_firstname == true) {
echo "Name - ". $pending_firstname . " " . $pending_lastname . "</br>" .
"Username - ". $pending_username . "</br></br>"
?>
</form>
<button id="approve" type="submit" form="status" name="approve" value="Approved">Approve</button>
<button id="deny" type="submit" form="status" name="deny" value="Denied">Deny</button><br><br><br>
<?php
;} else {
echo "There are no Pending Requests at this time.";
}
}
}
}
?>
AJAX call
<script>
$(document).ready(function(){
$('#submit').click(function(){
var id_val=$("#pending_id").val();
var id_val=$("#approve").val();
$.post("userRequest_approve.php", $("#status").serialize(), function(data) { });
$('#success').html('User Status Changed!');
$('#success').hide(2000);
});
});
</script>
userRequest_approve.php file
<?php
require_once 'core/init.php';
$term = mysql_escape_string($term); // Attack Prevention
$pending_id = $_POST['id'];
$status = $_POST['approve'];
$con = mysqli_connect("localhost","root","","db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $con->prepare("INSERT INTO user_requests (status, date_responded) VALUES (?, NOW())");
if ( false===$stmt ) {
// Check Errors for prepare
die('User Request update prepare() failed: ' . htmlspecialchars($con->error));
}
$stmt->bind_param('s', $status);
if ( false===$stmt ) {
// Check errors for binding parameters
die('User Request update bind_param() failed: ' . htmlspecialchars($stmt->error));
}
$stmt->execute();
if ( false===$stmt ) {
die('User Status update execute() failed: ' . htmlspecialchars($stmt->error));
}
?>
I think you javascript is the weakest part of your code, here is some simple example for your ajax call, just change some values around and try it out
$('.approve').click(function(){
$.ajax({
url: '/whereEver/itNeedsToGo',
data: {
id: $(this).val(), //the value of what you clicked on
status: 'Approved' //you clicked on it so you know the status might aswell hardcode it
},
success: function(data) {
//do something with the data that got returned
},
type: 'POST'
});
});
EDIT: i would make it a little "dirty" to achief what you want... there are more ways to solve it but for now i will do it the easy way....
change ID into class
<button class="approve" type="submit" form="status" name="approve" value="<?=$pending_id;?>">Approve</button> give the approve button the value of the pending ID..... and i edit the ajax call above accordingly....this should work

Categories