Javascript: Can't delete after the Confirmation Message - javascript

Here's my scenario:
I have a form, main_play.php, where its a list of all playlist then when I click the radio button it will pop up a confirmation message then after that it will proceed to the form of play_delete...Proceeding in the next page is working...
But in the play_delete.php all variables there are already empty... But, when I'm not using the confirmation message it can be deleted and also the variables are transferred in play_delete...
Here's my variable:
$get_ID = $_POST['deletePlaylist'];
Here's my code for PHP:
<input type="radio" name="deletePlaylist[]" class="chk_boxes1" value="<?php echo $row['id']; ?>"<?php echo ($_POST['deletePlaylist[]'] == $row['id'] ? 'checked=" checked"' : ''); ?> onclick='confirmation()'>
Here's my javascript:
<script>
function confirmation() {
var answer = confirm("Are you sure you want to delete?")
if (answer){
window.location = 'play_delete.php';
}
else{
alert("Thanks for sticking around!")
}
}
</script>
Is there a way to transfer the data in php to javascript then javascript to the next page??
Thanks in advance!

Replace
window.location = 'play_delete.php';
with
document.formname.action = 'play_delete.php';
document.formname.submit();
where formname is the name of the form on the page in which all the playlist radio buttons are appearing.

try this it will work
<script>
function confirmation(value) {
var answer = confirm("Are you sure you want to delete?")
if (answer){
window.location = 'play_delete.php?data='+value;
}
else{
alert("Thanks for sticking around!")
}
}
</script>
<body>
<input type="radio" name="radio" value="uniqvalue" id="name" onclick='confirmation(this.value);'/>
</body>

Have a look at this for transferring a PHP variable to a javascript variable:
How to access PHP variables in JavaScript or jQuery

Related

How to call javascript function from form in a php echo?

what the bellow code does is making sure the user isn't allowed to submit a comment unless he's signed in by using $_SESSION['login_user'] supervariable. But it's giving me an error. I think the problem is because I'm calling a javascript function in onsumbit="return(checkUser())". There's something wrong there but I don't know why.
I have the following code:
<script type="text/javascript">
// notice the quotes around the ?php tag
function checkUser() {
<?php
if(isset($_SESSION['login_user'])){
$isExist = true;
}
?>
else{
$isExist= false;
alert( "Please register first!" );
}
var htmlString="<?php echo $isExist; ?>";
return isExist;
}
</script>
...
...
<?php
echo "<form method='POST' onsubmit="return(checkUser());" action='".setComments($connection, $res['post_id'])."'>
//echo "<form method='POST' action='".setComments($connection, $res['post_id'])."'>
<input type='hidden' name='uid' value='".$_SESSION['login_user']."'>
<input type='hidden' name='date' value='".date('Y-m-d H:i:s')."'>
<textarea name='message'> </textarea><br>
<button type='submit' name='commentSubmit'>Comment</button>
</form>";
getComments($connection, $res['post_id']);
?>
....
If this is not the right method to stop the user from submitting a comment, then what could be another method?
In addition to what #RonaldT said, you need to understand that the PHP code is executed on the server before being sent to the browser. So checking for $_SESSION['login_user'] inside a Javascript function is kind of silly, since it will always be the same until the user refreshes the page (only then will PHP re-check the value).
So your function can be simplified like this:
<script type="text/javascript">
// on page load, define a global variable using PHP
var isLoggedIn = <?php echo isset($_SESSION['login_user']) ? "true" : "false"; ?>;
function checkUser() {
// check that global variable every time checkUser() is called in Javascript
if (!isLoggedIn) {
alert( "Please register first!" );
}
return isLoggedIn;
}
</script>
Keep in mind that this kind of "security" is extremely easy to fool (any user can just open their browser console, type isLoggedIn = true; and voila), so be sure to check on the server as well when the form is submitted.
Or better yet: if a user is not allowed to do something, don't give them the opportunity. Why display the form at all if the user will not be allowed to submit it anyway?
<?php
if (!isset($_SESSION['login_user'])) {
echo "Please register to add a comment";
} else {
echo "<form [...everything else...] /form>";
}
getComments($connection, $res['post_id']);
?>

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>

PHP loop value sent to javascript

I'm avoiding using a database for my latest project and so I am using files and folders. I list folders of a directory as buttons and each one loads a screen with a list of files within it. I'm now trying to load in the file's contents dynamically without refresh to avoid loosing the menu (list of files shown on screen as buttons). I'm trying to use ajax but because the file buttons are created using a foreach php loop, the value I pass to javascript/ajax when I click one of the file buttons is incorrect as it always wants to pass the first button's value in the list!
Here is the PHP code:
<?php
if(isset($_POST['FolderContent'])) {
foreach (glob($_POST['FolderContent']."/*.*") as $file) {
if(is_file($file)){
$fileNoExt = substr($file, 0, -4); //Remove file extension so the menu item shows only the name of the file
$character = explode('/', $fileNoExt);
$filePathTrimmed = trim(end($character));
echo "<form method='POST'>
<input type='submit' ID='selectBtn' value='$filePathTrimmed' onclick='return displayData();'/>
<input type='hidden' id='dataField' name='content' value='$file'/>
<input type='hidden' name='title' value='$filePathTrimmed'/>
</form>";
} else {
echo "Files not found!";
}
}
}
?>
And this is the JS:
<script>
function displayData()
{
var btnData = document.getElementByID('selectBtn').value;
alert("The currently selected button is "+btnData);
});
}
</script>
As you can see the PHP loops and creates a form for each button plus hidden fields. The JS just tries to grap the value of the button clicked and alert it. Problem is that the value is always the first file in the list.
What am I doing wrong please? If I use a class on the button instead of an ID then I will need to state the number in the array:
var btnData = document.getElementsByClassName('selectBtn')[0].value;
But this means I'd need to know the place within the array and make using the value pretty pointless.
I'm pretty stuck - or thick!
Thanks.
You need to use this inside onclick='return displayData(); and then use it in your function like below:-
Working snippet:-
function displayData(ele){
var btnData = ele.value;
alert("The currently selected button is "+btnData);
return false;
}
<form method='POST'>
<input type='submit' value='hi' onclick='return displayData(this);'/>
<input type='hidden' name='content' value='$file'/>
<input type='hidden' name='title' value='$filePathTrimmed'/>
</form>
You are setting the same id value for each separate form. You should ensure that all the id attribute values are unique for all html elements as a rule of thumb to avoid unpredictable behaviours in the dom.
<?php
if(isset($_POST['FolderContent'])) {
foreach (glob($_POST['FolderContent']."/*.*") as $idx => $file) {
if(is_file($file)){
$fileNoExt = substr($file, 0, -4); //Remove file extension so the menu item shows only the name of the file
$character = explode('/', $fileNoExt);
$filePathTrimmed = trim(end($character));
echo "<form method='POST'>
<input type='submit' id='selectBtn-{$idx}' value='$filePathTrimmed' onclick='return displayData(this.id);'/>
<input type='hidden' id='dataField' name='content' value='$file'/>
<input type='hidden' name='title' value='$filePathTrimmed'/>
</form>";
} else {
echo "Files not found!";
}
}
}
?>
And javascript:
<script>
function displayData(clicked_id)
{
var btnData = document.getElementByID(clicked_id).value;
alert("The currently selected button is "+btnData);
return false;
}
</script>
Solution: I used 'return false' at the end of the javascript/ajax code block, and 'this' in the php code to pass current data held in 'value' - thanks Alive to Die.
I also I made use of the 'name' attribute to store and access further data data.
PHP:
echo "<form method='POST'>
<input type='submit' id='selectBtn' name='$file' value='$filePathTrimmed' onclick='return displayData(this);'/>
</form>";
JS:
<script>
function displayData(fileName)
{
var btnData =fileName.name;
var name = fileName.value;
$.ajax({
type : "POST",
url : "DisplayFileContents.php",
data : {"data": btnData, "name": name},
success : function(result) {
$('.page-content').html(result);
$('body').animate({scrollTop: 0}, 200);
}
});
return false;
};
DisplayFileContents.php:
<?php
$filename=$_POST['data'];
$title = $_POST['name'];
echo "<h2>".$title."</h2>";
echo "<pre>";
Include $filename;
echo "</pre>";
?>

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>

AJAX Call to PHP File for HTML Form Not Working

I have a login-form created using HTML that looks like this:
<div class= "form-header">Login</div>
<div class= "error-message" id= "login-error-exists"></div>
<form action= "login.php" method= "POST" onsubmit= "loginCheckIncorrect()">
<div class= "form-field">
<div class= "form-text">
username:
</div>
<input type= "text" class= "login-textbox" id= "login-login-username" name= "loginLoginUsername">
</div>
<div class= "form-field">
<div class= "form-text">
password:
</div>
<input type= "password" class= "login-textbox" id= "login-login-password" name= "loginLoginPassword">
</div>
<input type= "submit" value= "Login" class= "signup-confirm">
</form>
As you can see, its a simple form that is sent to login.php though POST. Upon submitting this form, it calls a JavaScript (using jQuery) function known as loginCheckIncorrect(), which is shown below:
function loginCheckIncorrect() {
"use strict";
var loginLoginUsername = $("#login-login-username").val(), loginLoginPassword = $("#login-login-password");
alert("test1");
$.post('usernameIncorrect.php', {'loginLoginUsername': loginLoginUsername, 'loginLoginPassword': loginLoginPassword}, function (data) {
$("#login-error-exists").html(data);
alert("test2");
event.preventDefault();
return false;
});
alert("test3");
event.preventDefault();
return false;
}
As you can see, this function creates the variables to store the value of username and password entered in each textbox. It sends an alert out (debugging), and then uses a jQuery.post function to send the variables to the PHP file, which I will show below. It then (is supposed to) takes the data sent back from the PHP file to echo into the error div I have in my HTML form.
It then calls an alert (more debugging) and uses a combination of event.preventDefault() and return false to (supposedly) stop the form from submitting. This is repeated after the post function.
This is my PHP code:
<?php
header("X-XSS-Protection: 1");
include("connect.php");
$username = mysqli_real_escape_string($con, $_POST["loginLoginUsername"]);
$password = mysqli_real_escape_string($con, $_POST["loginLoginPassword"]);
echo "<script>alert('test');</script>";
$sql = mysqli_query($con, "SELECT * FROM main WHERE username='$username' and password='$password'");
$count = mysqli_num_rows($sql);
if ($count == 1) {
echo "";
$_SESSION["username"] = $username;
$_SESSION["password"] = $password;
} else {
echo "username and/or password is incorrect.";
}
?>
When I attempt to execute this code, the only alert it displays is test1. Could someone explain to me why this is, and more importantly, how I can fix it? Thanks in advance.
Look at your network requests in your browser's debug panel to see if it's sending what you think it is, put some debug statements in your PHP to see what is and isn't getting hit.
In this case, I think you might be missing the .val() on $('login-login-password') just before the alert("test1") in your javascript.
There is no event defined. That would be a problem and the form will submit. And the preventDefault in the callback is useless since the function already finished.
1) The name of the php file is login.php
2) The url to which you are requesting the post is usernameIncorrect.php
Therefore:
$.post('login.php', {'loginLoginUsername': loginLoginUsername, 'loginLoginPassword': loginLoginPassword}, function (data) {
$("#login-error-exists").html(data);
alert("test2");
event.preventDefault();
return false;
});
Alert test1 is the only one appearing because the post fails.
Probably with a fail event you would have cached the error.
Try, if you want to test that:
$.post('wrongUrl.php', {'loginLoginUsername': loginLoginUsername, 'loginLoginPassword': loginLoginPassword}, function (data) {
$("#login-error-exists").html(data);
alert("test2");
event.preventDefault();
return false;
})
.fail(function() {
alert( "error" );
});

Categories

Resources