Passing variable with button (Ajax Modal) - javascript

In table (that contains records, customers credentials, from my db) I have a delete button for each row.
I want that if I click on the delete button, this will delete the row, passing the ID of the record to the deletecustomer.php
When I click on the delete button, I have a ajax modal that ask if you want to confirm the action or not.
The problem is that if I click on CONFIRM (in the modal), my modal will go in delete-utente.php (where I have the query for the delete of the row) but the ID isn't passed.
In delete-utente.php I have a message if the query it's ok (delete complete), and another message if the delete can't be done.
After I click confirm I always have the OK message, but the customer has not been deleted.
I guess that the problem is not the deletecustomer.php because if I use a simple javascript alert, the query it's ok and I pass the identifier successful, but with the ajax modal, the identifier is not passed.
It's the first time that I use ajax, so I think that the problem it's ajax code.
code of the table in my main page (newcustomer.php)
<table class="simple-table responsive-table" method="POST" id="customer-list">
//code thead
//rows rows..
<?php echo '<button type="input" class="button icon-trash with-tooltip confirm" onclick="openConfirm()" href="deletecustomer.php?customerid='.$idcustomer.'" title="Delete"></button>'; ?>
//....
</table>
ajax modal
function openConfirm()
{
$.modal.confirm('Sicuri di voler cancellare il cliente?', function()
{
window.location.href = "deletecustomer.php"; //the php file where I have the delete query
}, function()
{
window.location.href = "newcustomer.php";
});
};
and I take the values in my deletecustomer.php like this
$customeridd=(int) $_GET['customerid'];
Sorry if is a stupid mistake or a stupid question ^^"
And thank in advice

You can use like this :
<?php
echo '<button type="input" class="button icon-trash with-tooltip confirm" onclick="openConfirm('.$idcustomer.')" href="deletecustomer.php?customerid='.$idcustomer.'" title="Delete">button</button>';
?>
And
function openConfirm(id)
{
alert(id);
$.modal.confirm('Sicuri di voler cancellare il cliente?', function()
{
window.location.href = "deletecustomer.php?customerid="+id; //the php file where I have the delete query
}, function()
{
window.location.href = "newcustomer.php";
});
};

Try the following code:
<?php echo '<a class="button icon-trash with-tooltip confirm" onclick="return confirm(\'Are you sure?\');" href="deletecustomer.php?customerid='.$idcustomer.'">Delete</a>'; ?>

Related

How to prevent form refresh but submit form data on same page?

My form kept submitting and then refreshing so I looked at How to prevent page from reloading after form submit - JQuery to figure out how to stop it. The difference in the answer, however, with my solution was that I was submitting the form to itself.
Here's my code:
HTML
<form autocomplete="off" method="post" name="rp">
<input placeholder="Code" type="text" name="code" required>
<button type="submit">Submit</button>
</form>
PHP
<?php
$response = "";
if(isset($_POST['code'])){
echo "<script> alert('test'); </script>";
$password = $_POST["code"];
$result = $connection->query("SELECT * FROM Users WHERE passwords = '$password' LIMIT 1");
if($result->num_rows != 0) {
// unpack object
$data = mysqli_fetch_array($result);
// retrieves user ID (set into a cookie for x amount of time?)
$id = $data["ID"];
mysqli_close($connection);
echo "<script> alert('test 2'); </script>";
$response = "test 2";
header("Location: assessment.php");
} else {
$response = "test 3";
echo "<script> alert('test 3'); </script>";
mysqli_close($connection);
}
}
?>
JS
$("form").submit(function (e) {
// prevent page refresh
e.preventDefault();
var formData = $(this).serialize();
// Make AJAX request
$.post("login.php", formData);
});
I want the form to submit the data but not refresh. What am I doing wrong?
EDIT:
The problem has been narrowed down to the php. Since the request is through javascript, what should the name in the if-statement argument be. It can't be 'rp'.
So I found out something extremely curious. When I changed the if statement to if(isset($_POST['code']){} as some urged me to in the comments and I entered in the correct password, it follows the correct loop and produces this error:
VM1368 jquery.min.js:2 GET http://localhost:8080/assessment 404 (Not Found)
However, it does not produce the alert code I place before the header(). When I put in an incorrect password, it also doesn't do anything (even though I have an else statement). I've updated the php section to include most of the code. The $response variable and the echo/alerts are for debugging.
Final Edit:
Ironically, the reason none of my debugging wasn't working was because the page wasn't refreshing so alerts and variable updates wouldn't happen. (My quest to stop page refresh created all these problems). The solution to my original question was provided by MH2K9 and Toni Michel Caubet in the comment section. Thank you to them and others who tried to help.
Try this :
HTML :
<form autocomplete="off" method="post" name="rp" onsubmit="return false;">
<input placeholder="Code" type="text" name="code" required>
<br>
<button type="submit">Submit</button>
<button id="back_button" type="button"><img src="pics/back_arrow.png">Back</button>
</form>
JS:
$("form").submit(function (e) {
// prevent page refresh
e.preventDefault();
var formData = $(this).serialize();
// Make AJAX request
$.post("login.php", formData , function(data) {
alert(data);
$("form").reset();
});
});
You can alternatively call a function using the onsubmit attribute in HTML.
<form onsubmit='return preventSubmit(e)'>
// form content
</form>
<script>
function preventSubmit(e) {
e.preventDefault()
return false
}
</script>

Toggle with an IF statement needs two clicks to fire

This is a toggle of a ‘follow-unfollow’ button of a Twitter like following system. When the button has the class unfollow it takes two clicks to trigger to fire. When the button has the class follow it fires in one click. This is related to the if statement. If the script does not need to run through the if statement it fires well on one click which is the part of the else section of the script. It is worth noting, that when two clicks are needed, if there is no refresh in the page, you then can toggle back and forth with just one click as it is supposed to be. Do you know how can I avoid using two clicks when the script needs to go through the if statement?
Thanks in advance.
<button class="followUnfollow" id="boton<?php echo $member->id; ?>" type="button" data-member_id="<?php echo $member->id; ?>" user_id="<?php echo $id;?>"> <?php echo $status; ?> </button>
<script>
$(document).ready(function() {
$("#boton<?php echo $member->id; ?>").on('click', function() {
var memberId = $(this).attr('data-member_id');
var userId = $(this).attr('user_id');
if($("#boton<?php echo $member->id; ?>").hasClass('unfollow')) { // TWO CLICKS TO FIRE
$.get("follow_actions.php", {unfollow_id:memberId, user_id:userId} , function(data) {
});
$(this).html('follow');
$(this).removeClass('unfollow').addClass('follow');
} else { // WORKS WELL, ONE CLICK TO FIRE
$.get("follow_actions.php", {follow_id:memberId, user_id:userId} , function(data) {
});
$(this).html('unfollow');
$(this).removeClass('follow').addClass('unfollow');
}
});
});
</script>

Jquery Post not working correctly?

I have been working on Like and Unlike feature with jquery, ajax and php. My problem is little bit difficult to understand. Lets try to understand it first.
I have 2 php pages, viewProfile.php and LikeMail.php. LikeMail.php is being called by ajax function in viewProfile.php.
Here is Section of viewProfile.php page's description
-----------------
| Like/Unlike |
-----------------
Here is button which actually comes from LikeMail.php by this ajax function
function like()
{
var req = new XMLHttpRequest();
req.onreadystatechange = function()
{
if(req.readyState==4 && req.status==200)
{
document.getElementById('Like').innerHTML=req.responseText;
}
}
req.open('POST','LikeMail.php','true');
req.send();
}
setInterval(function(){like()},1000);
HTML:
<div id="Like"></div>
Output is being shown here in this div. Button above may be Like or Unlike depends on the condition in LikeMail.php which will be described below in LikeMail.php description section.
When one of them (buttons) Like or Unlike is clicked. It then calls respective jquery click function which sends post request to LikeMail.php.I have mentioned Indirect page in title because Like or Unlike buttons actually exists in LikeMail.php page. But due to ajax call these buttons are being shown in viewProfile.php page. So I then send post requests through viewProfile.php to actual page LikeMail.phpIt is jquery post for Unlike button
$(document).ready(function(){
$('#Unlike').unbind().click(function(){
$.post("LikeMail.php",
{Unlike: this.id},
function(data){
$('#response').html(data);
}
);
});
});
It is jquery post or Like button
$(document).ready(function(){
$('#Like').unbind().click(function(){
$.post("LikeMail.php",
{Like: this.id},
function(data){
$('#response').html(data);
}
);
});
});
End of description section of viewProfile.php page
Here is Section of LikeMail.php page's description
Like or Unlike button is shown in viewProfile.php page depends upon this code:
$check_for_likes = mysqli_query($conn, "SELECT * FROM liked WHERE user1='$user1' AND user2='$user2'");
$numrows_likes = mysqli_num_rows($check_for_likes);
if (false == $numrows_likes) {
echo mysqli_error($conn);
}
if ($numrows_likes >= 1) {
echo '<input type="submit" name="Unlike" value="Unlike" id="Unlike" class="btn btn-lg btn-info edit">';
}
elseif ($numrows_likes == 0) {
echo '<input type="submit" name="Like" value="Like" id="Like" class="btn btn-lg btn-info edit">';
}
Button depends upon these two above conditions.
Now when Like button is clicked, post request from viewProfile.php comes here
if(isset($_POST['Like'])) //When Like button in viewProfile.php is clicked then this peace of code inside if condition should run and insert some record in database
{
$total_likes = $total_likes+1;
$like = mysqli_query($conn, "UPDATE user SET user_Likes = '$total_likes' WHERE user_id = '$user2'");
$user_likes = mysqli_query($conn, "INSERT INTO liked (user1,user2) VALUES ('$user1','$user2')");
$query3 = "INSERT INTO notification (user1, user2, alert, notificationType) VALUE ('$user1','$user2','unchecked','like')";
if (mysqli_query($conn, $query3)) {
echo "Like";
} else {
echo mysqli_error($conn);
}
}
Similarly when Unlike button is clicked. This peace of code should run.
if(isset($_POST['Unlike'])) //This is the condition for Unlike button. It should delete record from databse
{
$total_likes = $total_likes-2;
$like = mysqli_query($conn, "UPDATE user SET user_Likes='$total_likes' WHERE user_id='$user2'");
$remove_user = mysqli_query($conn, "DELETE FROM liked WHERE user1='$user1' AND user2='$user2'");
$query3 = "DELETE FROM notification WHERE user1='$user1' AND user2='$user2' AND notificationType='like'";
$check = mysqli_query($conn, $query3);
if ($check) {
echo "Unlike";
} else {
echo mysqli_error($conn);
}
}
Problem:
Main problem which I faced is that when I click Like or Unlike both executes the condition of Like button code. Both inserts the data into database as Unlike condition should delete data from database but it also inserts data as condition for Like button do. Kindly can you please help me that how to tackle this problem. Thanks in advance!
Update:When I delete all the respective code for Like button. The condition for Unlike button starts working correctly.
I think there's a duplicated ID somewhere, perhaps the DIV. Take a look at this.
<div id="Like_2"></div>
<input type="submit" name="Unlike" value="Unlike" id="Unlike" class="btn btn-lg btn-info edit">
<input type="submit" name="Like" value="Like" id="Like" class="btn btn-lg btn-info edit">
<div id="response"></div>
$(document).ready(function(){
$(document).on('click','#Unlike', function(){
$('#response').html(this.id);
//ajax call
});
$(document).on('click','#Like', function(){
$('#response').html(this.id);
//ajax call
});
});
And the javascript function:
function like()
{
var req = new XMLHttpRequest();
req.onreadystatechange = function()
{
if(req.readyState==4 && req.status==200)
{
document.getElementById('Like_2').innerHTML=req.responseText;
}
}
req.open('POST','LikeMail.php','true');
req.send();
}
setInterval(function(){like()},1000);
https://jsfiddle.net/wx38rz5L/2103/

Correct method of sending a variable from a html form to a php function via ajax

I'm coding a voting system for multiple uploads; each uploaded image is in a foreach statement with a form attached to each, with three buttons to vote up, down or none, each associated with an INT in my mysql database.
I got it to work by submitting the form data straight to the PHP function that 'UPDATE's the database. To avoid a page refresh, I attach ajax. I got the ajax to send the two variables needed for the PHP function to update the correct "image" row and INT in the db.
Question: The ajax function works, but the PHP function doesn't seem to update.
SUSPECTED PROBLEM: I'm pretty sure it's the way I'm defining the variables in ajax that I want to pass, I was trying to grab the ID of the "image" it's handling, but I don't know how to translate this data to the PHP function so that it UPDATE's correctly.
Here's the form, javascript, and php:
// IMAGE, and rest of foreach above this, and ending after form
// This form only shows one button, there are three, each
// I'll treat the same once I get one to work
<form action="feed.php" method="post" id="vote_form_1">
// If js isn't turned on in broswer, I keep this
// hidden input, to send unique ID
<input type="hidden" name ="input_id"
class="input_id" value="<?php echo $row['id']; ?>"/>
<input type="submit" name="post_answer1" onclick="sayHi(event);"
class="answer_L" id="<?php echo $row['id']; ?>"
value="<?php echo $row['post_answerL']; ?>"/>
</form>
// end of foreach
//AJAX
<script type="text/javascript">
function sayHi(e) {
var input_id = $(e.currentTarget).attr('id');
var post_answer1 = $("input[name='post_answer1']");
jQuery.ajax({
type: 'POST',
url: 'feed.php', //name of this file
data:input_id,post_answer1,
cache: false,
success: function(result)
{
alert ('It worked congrats');
}
});
e.preventDefault();
</script>
// PHP VOTE UPDATE FUNCTION
<?php>
if(isset($_POST['post_answer1'],$_POST['input_id'])){
$current_id = $_POST['input_id'];
$vote_1 = "UPDATE decision_post set " .
"post_answer1=post_answer1+1 WHERE id = '".$current_id."' ";
$run_vote1 = mysqli_query($conn2, $vote_1);
if($run_vote1){ echo 'Success'; }
}
?>
Here a simple answer, just serialize all your form data!
$('form').submit(function(){
$.post('feed.php', $(this).serialize(), function(data){
console.log(data);
}, 'json');
return false;
});
var post_answer1 = $("input[name='post_answer1']").val();

How to make a button reusable after the first click with AJAX/JQUERY and PHP

I have built a follow/unfollow Twitter like system using PHP. With help of this forum I have been successful creating a dynamic button that allows you to “follow” or “unfollow” each user, using AJAX/JQUERY to run the PHP/MySQL code in the back and avoid refreshing the page when the action happens. The thing is that I am able to run this script on the background only once. Let’s say a user unfollows a member by mistake (my AJAX/JQUERY script won’t have any problem with that), but then wants to follow him again, this is where I am stuck. The page will have to be refresh to make this happen. I know this is happening due to the PHP dynamic data that I am using as you will see in my code.
In the PHP code am running an iteration that output all the members in the database. I am outputting here (for simplicity) just the member’s name and a follow/unfollow button to each one. The php variable $what_class is the result of a PHP function that looks into the database to determine if the user is following or not that member. $what_class will output the strings “follow” of “unfollow” so the class can be defined, and then be targeted by either of the two the Jquery scripts.
PHP CODE
<?php foreach($members as $member){ ?>
<p class="member_name"><?php echo $member->name; ?></p>
<button class="<?php echo $what_class; ?>" type="button" data-member_id="<?php echo $member->id; ?>" user_id="<?php echo $id;?>" ><?php echo $what_class; ?></button>
<?php } ?>
Below is the JQUERY scripts, as mentioned before, the button class will be defined by PHP through $what_class. This is the problem when trying to re-use the button after the first time, class won´t change in PHP’s $what_class unless the page is refreshed. I tried to use $(this).removeClass('unfollow').addClass('follow') to change the class using Jquery and have the button to be re-usable but it isn’t working.
JQUERY SCRIPTS TO FOLLOW OF UNFOLLOW
<script type="text/javascript">
$(document).ready(function() {
$("button.unfollow").on('click', function() {
var memberId = $(this).attr('data-member_id');
var userId = $(this).attr('user_id');
$.get("follow_actions.php", {unfollow_id:memberId, user_id:userId} , function(data) {
});
$(this).html('follow');
$(this).removeClass('unfollow').addClass('follow');
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$("button.follow").on('click', function() {
var memberId = $(this).attr('data-member_id');
var userId = $(this).attr('user_id');
$.get("follow_actions.php", {follow_id:memberId, user_id:userId} , function(data) {
});
$(this).html('unfollow');
$(this).removeClass('follow').addClass('unfollow');
});
});
</script>
Does anyone knows how I accomplish having a reusable button without reloading the page? I thank you in advance.
Previous Answer:
What I do for that kind of scenario is to have two buttons. One will be shown to the user, and the other one will be hidden.
<button class="follow" data-member_id="<?php echo $member->id; ?>" user_id="<?php echo $id;?>" >Follow</button>
<button class="unfollow" style="display:none" data-member_id="<?php echo $member->id; ?>" user_id="<?php echo $id;?>" >Unfollow</button>
Just tweak your php code what to show and what not.
When a button is click, hide this button and show the other one.
$(document).ready(function(){
$(".follow").on("click", function(){
$(".follow").hide(200);
$(".unfollow").show(200);
/* PUT YOUR OTHER PROCESSES HERE */
});
$(".unfollow").on("click", function(){
$(".follow").show(200);
$(".unfollow").hide(200);
/* PUT YOUR OTHER PROCESSES HERE */
});
});
Check this JSfiddle.
Update:
We can use toggleClass() of jQuery.
<button class="follow" data-member_id="12" user_id="12">Follow</button>
And the script:
$(document).ready(function(){
$(".follow, .unfollow").on("click", function(){
var memberId = $(this).attr('data-member_id');
var userId = $(this).attr('user_id');
$(".follow, .unfollow").toggleClass("follow unfollow");
$(this).text(function(i, text){
return text === "Follow" ? "Following" : "Follow";
});
});
});
Check this JSfiddle.
use <button class="followUnfollow <?php echo $what_class; ?>"
You need to write as less code as possible. Have a common class such as followUnfollow and then check if follow class exists within this element using hasClass function from jQuery.
Have a look at the code below.
<script type="text/javascript">
$(document).ready(function() {
$("button.followUnfollow").on('click', function() {
var memberId = $(this).attr('data-member_id');
var userId = $(this).attr('user_id');
if($(this).hasClass('follow')) { // FOLLOW
$.get("follow_actions.php", {follow_id:memberId, user_id:userId} , function(data) {
});
$(this).html('unfollow');
$(this).removeClass('follow').addClass('unfollow');
} else { // UNFOLLOW
$.get("follow_actions.php", {unfollow_id:memberId, user_id:userId} , function(data) {
});
$(this).html('follow');
$(this).removeClass('unfollow').addClass('follow');
}
});
});
</script>

Categories

Resources