DB ROW update with AJAX - php

i am troubleshooting with update row using AJAX. When i click submit button, the value of poke increases +1 and i need it to update in DB also. Everything needs to work with AJAX.
Currently my code works only +1 to poke input with ajax but DB row still not updating.
HTML:
<?php
$result = $mysqli->query("SELECT * FROM users") or die($mysqli->error);
while ($users = $result->fetch_assoc()) {
?>
<form class="table" name="table" id="table" method="post" enctype="multipart/form-data" autocomplete="off" data-counter="<?php echo $users['id']?>">
<div class="Table-row" id="table">
<div class="Table-row-item" data-header="Header1"><input class="clear" type="text" name="first_name" id="first_name" value="<?php echo $users['first_name'] ?>"></div>
<div class="Table-row-item" data-header="Header2"><input class="clear" type="text" name="last_name" id="last_name" value="<?php echo $users['last_name'] ?>"></div>
<div class="Table-row-item" data-header="Header3"><input class="clear" type="text" name="email" id="email_<?php echo $users['email']?>" value="<?php echo $users['email'] ?>"></div>
<div class="Table-row-item" data-header="Header4"><input class="clear" type="text" name="poke" id="poke_<?php echo $users['id']?>" value="<?php echo $users['poke']?>"></div>
<div class="Table-row-item" data-header="Header5"><input class="poke" type="submit" value="Poke" id="submit" name="submit"></div>
<input class="clear" type="hidden" id="hidden" name="hidden" value="<?php echo $users['email']?>">
</div>
</form>
<?php
} ?>
PHP:
<?php
require 'db.php';
if (isset($_POST['submit'])) {
$poke = $mysqli->escape_string($_POST['poke']);
$email = $mysqli->escape_string($_POST['email']);
$mysqli->query("UPDATE users SET poke='$poke' WHERE email='$email'") or die($mysqli->error);
}
AJAX:
$(document).ready(function () {
$('form').on('submit', function (e) {
var id = $(this).attr('data-counter');
e.preventDefault();
$.ajax({
type: "post",
data: $(this).serialize(),
url: "update.php",
success: function () {
var counter = parseInt($("#poke_"+id).val()); // Use form's inner #poke
counter++;
$("#poke_"+id).val(counter);
alert("form was submited on: " + id);
}
});
return false;
});
});

Not enough info. You need to do more diagnostics.
E.g: Dump the SQL statement to the output so you can check it is what you expect it to be.
And run the SQL in, e.g. phpAdmin to check if it updates.
You may have a problem in the email string, which could be caused by, say, different character encodings between AJAX and the DB. Probably both should use UTF8.

Related

How to add form to access page number in instant search?

I used this script (https://www.webslesson.info/2020/02/instant-search-with-pagination-in-php-mysql-jquery-and-ajax.html) and I would like to add a form to directly access a page number.
I tried this but it doesn't work !
<div class="goto-page">
<form action="" method="POST" onsubmit="return pageValidation()">
<input type="submit" class="goto-button" value="Go to page">
<input type="text"
class="enter-page-no" maxlength="4" size="3"
name="goto" min="1"
required >
</form>
</div>
PHP Code modified
if (isset($_POST['goto'])) {
$start = (($_POST['page'] - 1) * $limit);
$page = $_POST['goto'];
}
else
{
if($_POST['page'] > 1)
{
$start = (($_POST['page'] - 1) * $limit);
$page = $_POST['page'];
}
else
{
$start = 0;
}
}
Consider the following example. This expands on the jQuery already in use in the example you linked to.
$(function() {
function load_data(page, query = '') {
$.ajax({
url: "fetch.php",
method: "POST",
data: {
page: page,
query: query
},
success: function(data) {
$('#dynamic_content').html(data);
}
});
}
load_data(1);
$(document).on('click', '.page-link', function() {
var page = $(this).data('page_number');
var query = $('#search_box').val();
load_data(page, query);
});
$('#search_box').keyup(function() {
var query = $('#search_box').val();
load_data(1, query);
});
$(".goto-page form").submit(function(evt) {
evt.preventDefault();
load_data(parseInt($(".goto-page input[name='goto']").val()));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<br />
<div class="container">
<h3 align="center">Live Data Search with Pagination in PHP Mysql using Ajax</h3>
<br />
<div class="card">
<div class="card-header">Dynamic Data</div>
<div class="card-body">
<div class="form-group">
<input type="text" name="search_box" id="search_box" class="form-control" placeholder="Type your search query here" />
</div>
<div class="table-responsive" id="dynamic_content">
</div>
<div class="goto-page">
<form>
<button type="submit">Go To Page</button>
<input type="text" class="enter-page-no" maxlength="4" size="3" name="goto" value="1" required>
</form>
</div>
</div>
</div>
</div>
When Enter is hit or the Button pressed, the form is submitted. The submit callback will gather the value and use load_data() to load that page.

Different values returned for php session variable

I have been having this problem for the last two days now. I have two files on my local host.
http://localhost/project/sign-in.php and
http://localhost/project/form-handle/index.php
When a user lands on sign-in page a session variable is created
<?php
ob_start();
session_start();
$token = strtoupper(uniqid());
$_SESSION['token-string'] = $token;
I then put the session value in a hidden field
<input type='hidden' name='token-string' value='<?php echo $token; ?>'>
So far, so good. However, when I send the form values to http://localhost/project/form-handle/index.php
and return the value of the token string session, its different from what is in the hidden field. I am using jquery ajax to send the request.
Here is how I check for it in the form-handle page:
<?php
ob_start();
session_start();
if(isset($_SESSION['token-string'])){
$token = $_SESSION['token-string'];
echo $token;
}
?>
The value returned is totally different! Its important to know also that the wrong value returned is a string generated by the function
strtoupper(uniqid());
Am I doing something wrong here?
Here is the jQuery that submits the form
$('#service-login').click(function (evt) {
evt.preventDefault();
var form = $('#Ads-Login');
var data = form.serialize();
var url = 'form-handle/index.php';
var method = form.attr('method');
$.ajax({
type: method,
url: url,
data: data,
success: function (response) {
alert(response);
},
error: function () {
}
})
});
The html form is here
<form action="" method="post" id="Ads-Login">
<div class="form-group">
<input type="email" name="email" id="" class="form-control" placeholder="Email Address">
</div>
<div class="form-group">
<input type="hidden" name="token-string" value="<?php echo $token; ?>">
<input type="password" name="Password" id="" class="form-control" placeholder="Account Password">
<a class="btn btn-white dark-grey-text font-bold ml-0" href="" id="service-login"><i class="fa fa-play mr-1"></i> Login</a>
</div>
</form>

Ajax get dynamic id for the submit button of the form PHP MySQL

I have a form in PHP & MySQL and I want to submit it with AJAX.
I Have similar data so I have put these data in a foreach loop.
The problem is that when I try to submit the first row data it all goes well but it changes the data in all rows. and when I try to submit other data except the first row it doesn't submit at all.
I think the problem is because the submit button always gets the same id and therefore goes to the first row always.
I don't know how to get the value in Ajax.
Here goes the code:
//php form
<?php
$pid = $_GET['pid'];
include('config.php');
$timeline_query="SELECT * FROM timeline_table WHERE pid=$pid";
$result_timeline=mysqli_query($conn,$timeline_query);
if(!$result_timeline){
echo "Error: " . $conn->error;
}
$timelines=array();
while($row_timeline=mysqli_fetch_assoc($result_timeline)){
$timelines[]=$row_timeline;
}
?>
<?php
$x = 0;
foreach ($timelines as $timeline):?>
<div class="card">
<div class="card-header" id="heading<?php echo $x; ?>">
<h5 class="mb-0">
<button class="btn btn-link" data-toggle="collapse" data-target="#collapse<?php echo $x; ?>" aria-expanded="true" aria-controls="collapse<?php echo $x; ?>">
<?php echo $timeline['timeline_title'];?>
</button>
</h5>
</div>
<div id="collapse<?php echo $x; ?>" class="collapse" aria-labelledby="heading<?php echo $x; ?>" data-parent="#accordion">
<div class="card-body">
<form id="register_form">
<input type="text" id="tid" name="tid" value="<?php echo $timeline['tid']; ?>"/>
<textarea class="form-control" rows="4" id="timeline_description" name="timeline_description"><?php echo $timeline['timeline_description'];?></textarea>
<input id="submit" type="submit" name="submit" value="Submit" />
</form>
</div>
</div>
</div>
<?php $x++; endforeach;
// ajax function
$(document).ready(function(){
$("#submit").click(function(){
var timeline_description = $("#timeline_description").val();
var tid = $("#tid").val();
alert(timeline_description);
alert(tid);
// Returns successful data submission message when the entered information is stored in database.
// var dataString = 'timeline_description='+timeline_description+'&pid='+ pid + '&tid='+ tid +;
var dataString = 'timeline_description='+timeline_description;
alert(dataString);
if(timeline_description=='')
{
alert("Please Fill All Fields");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "process.php?tid"=+tid,
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
//process.php
<?php
include('config.php');
$tid=$_GET['tid'];
if( $_POST['timeline_description']==NULL ){ $timeline_description=''; }
else { $timeline_description=$_POST['timeline_description']; }
$query_timeline = "UPDATE timeline_table SET
timeline_description='$timeline_description' WHERE tid=$tid ";
$result=mysqli_query($conn,$query_timeline);
if(!$result){
echo "Error: " . $conn->error;
}
?>
Any idea?
Id of elements must be unique. The abnormal behaviour of your code is due to non-unique ids of your input elements.
In the case, If you cannot assign unique ids to elements you can achieve desired output by using this keyword and siblings() method in jquery.
Instead of
var timeline_description = $("#timeline_description").val();
var pid = $("#pid").val();
var tid = $("#tid").val();
try to get values in this way.
var timeline_description = $(this).siblings('#timeline_description').val();
var pid = $(this).siblings('#pid').val();
var tid = $(this).siblings('#tid').val();
I see there a problem with Yours inputs id - <input type="text" id="pid" - this is in foreach, so You have multiple elements with same id. So var pid = $("#pid").val(); will return You always a value of first found element. Try to use arrays:
<input type="text" id="pid[$pid]" name="pid[$pid]" value="<?php echo $pid ?>"/>
<input type="text" id="tid[$pid]" name="tid[$pid]" value="<?php echo $timeline['tid']; ?>"/>
Please remember one thing: id of any element in html PAGE (whole document) must be unique.

Using Ajax to delete a database row only deletes the first row, not the selected row

I'm using the code below to loop through my database rows and display the info. Each form has a delete button that should delete that row from the database :
function show_scheduled_tweets () {
global $wpdb;
$query = "SELECT * FROM wp_tweettweet";
$results = $wpdb->get_results($query, ARRAY_A);
foreach($results as $result) {
$tweet2 = $result[text];
$recycleOption = $result[recycle];
$id = $result[id];
?>
<form id="tweet-<?php echo $id; ?>" class="tweetclass form-inline" action="" method="post">
<div class="checkbox">
<label>
<input type="checkbox" name="recycle" <?php if($recycleOption == 1){ echo "checked";} ?>>Recycle Tweet?
</label>
</div>
<div class="form-group"><input class="form-control" type="text" name="tweet" value="<?php echo $tweet2; ?>"></div>
<div class="form-group"><input class="form-control" type="text" name="tweetdate"></div>
<input type="hidden" name="id" value="<?php echo $id; ?>">
<div class="form-group"><input class="form-control" type="text" name="timepicker" class="timepicker"/></div>
<input class="tweetsubmit" type="submit" value="Save">
<input class="tweetdelete" type="submit" value="delete">
</form>
<?php
}
}
show_scheduled_tweets();
Here is my Ajax :
jQuery('.tweetdelete').click(function(event) {
event.preventDefault();
var id = jQuery('input[name="id"]').val();
jQuery.ajax({
type: "POST",
url: ajaxurl,
data: {
'action': 'db_tables_delete',
'id': id
},
beforeSend: function() {
alert('before')
},
success: function(){
alert('success')
},
error: function(){
alert('error')
},
});
});
Let's say I have five different rows of data showing. Now matter which delete button I click, the top row will always be deleted. In other words, if I click the delete button for row 3, the first row will be deleted.
As per your current code val() returns value of first element. Check the description from documentation :
Get the current value of the first element in the set of matched elements or set the value of every matched element.
You need to get the id value based on clicked element, use prevAll()
var id = jQuery(this).prevAll('input[name="id"]').val();
or siblings() method
var id = jQuery(this).siblings('input[name="id"]').val();
or with closest()(or parent()) and find()
var id = jQuery(this).closest('form').find('input[name="id"]').val();
Your selector for the US is not particular to the tweet in the firm. The event passed to the JS function will carry with it a target (which will be the button that was clicked), if you echo your $id into a data attribute of that button then the relevant id it will be accessible within the target:
<input data-id="<?php echo $id;?>" class="tweetdelete" type="submit" value="delete">
and in your JS:
var id = jQuery(event.target).attr('data-id');

Load php form on submit

I have an admin panel where I have an option to add a user into database. I made a script so when you click the Add User link it will load the form where you can introduce the user infos. The thing is, I want to load in the same page the code that is run when the form is submited.
Here's the js function that loads the file:
$( ".add" ).on( "click", function() {
$(".add-user-content").load("add-user-form.php")
});
and here's the php form
<form id="formID" action="add-user-form.php" method="post">
<p>Add Blog Administrator:</p>
<input type="text" name="admin-user" value="" placeholder="username" id="username"><br>
<input type="password" name="admin-pass" value="" placeholder="password" id="password"><br>
<input type="email" name="admin-email" value="" placeholder="email" id="email"><br>
<input type="submit" name="add-user" value="Add User">
</form>
<?php
include '../config.php';
$tbl_name="blog_members"; // Table name
if(isset($_POST['add-user'])){
$adminuser = $_POST['admin-user'];
$adminpass = $_POST['admin-pass'];
$adminemail = $_POST['admin-email'];
$sql="INSERT INTO $tbl_name (username,password,email) VALUES('$adminuser','$adminpass','$adminemail')";
$result=mysqli_query($link,$sql);
if($result){
echo '<p class="user-added">User has been added successfully!</p>';
echo '<a class="view-users" href="view-users.php">View Users</a>';
}else {
echo "Error: ".$sql."<br>".mysqli_error($link);
}
}
?>
Maybe I was not that clear, I want this code
if($result){
echo '<p class="user-added">User has been added successfully!</p>';
echo '<a class="view-users" href="view-users.php">View Users</a>';
}else {
echo "Error: ".$sql."<br>".mysqli_error($link);
}
to be outputted in the same page where I loaded the form because right now it takes me to the add-user-form.php when I click the submit button.
Thanks for your help!
if you do this the code will be redirected on post to your page:
<form name="formID" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
you should add a validation so it doest show the form if you receive $_POST['add-user']
You have to submit your for via ajax.
Alternatively you don't need to load form html, just hide the form and on add user button click show the form.
Check this code. Hope that helps you :-
// Add User Button
<div class="color-quantity not-selected-inputs">
<button class="add_user">Add User</button>
</div>
// Append form here
<div class="add_user_form"></div>
// for posting response here
<div class="result"></div>
Script for processing form and appending user form
<script>
$(function(){
$( ".add_user" ).on( "click", function() {
$(".add_user_form").load("form.php")
});
$(document).on("submit","#formID", function(ev){
var data = $(this).serialize();
console.log(data);
$.post('handler.php',data,function(resposne){
$('.result').html(resposne);
});
ev.preventDefault();
});
});
</script>
form.php
<form id="formID" action="" method="post">
<p>Add Blog Administrator:</p>
<input type="text" name="admin-user" value="" placeholder="username" id="username"><br>
<input type="password" name="admin-pass" value="" placeholder="password" id="password"><br>
<input type="email" name="admin-email" value="" placeholder="email" id="email"><br>
<input type="submit" name="add-user" value="Add User">
</form>
handler.php
<?php
include '../config.php';
$tbl_name="blog_members"; // Table name
if(isset($_POST['add-user'])){
$adminuser = $_POST['admin-user'];
$adminpass = $_POST['admin-pass'];
$adminemail = $_POST['admin-email'];
$sql="INSERT INTO $tbl_name (username,password,email) VALUES('$adminuser','$adminpass','$adminemail')";
$result=mysqli_query($link,$sql);
if($result){
echo '<p class="user-added">User has been added successfully!</p>';
echo '<a class="view-users" href="view-users.php">View Users</a>';
}else {
echo "Error: ".$sql."<br>".mysqli_error($link);
}
die;
}
?>
What you are looking for is to submit the form using AJAX rather than HTML.
Using the answer Submit a form using jQuery by tvanfosson
I would replace your
<input type="submit" name="add-user" value="Add User">
with
<button id="add-user-submit">Add User</button>
and then register an onClick-handler with
$( "#add-user-submit" ).on( "click", function() {
$.ajax({
url: 'add-user-form.php',
type: 'post',
data: $('form#formID').serialize(),
success: function(data) {
$(".add-user-content").append(data);
}
});
});
to add the actual submit functionality.

Categories