I have a really silly issue i am trying to sort out. I have made this script that displays and deletes users from a database. however my alert function is not working. it performs the action of deleting the content in the database regardless of what I press when the alert appears. here is my code:
<?php include_once "includes/scripts.php"; ?>
<?php include_once "includes/connect.php";?>
<?php include_once "includes/cms_page_security.php";?>
<div id="cms_container"><br>
<br>
<h1>MANAGE USERS<img src="images/three_column_grid_line.png" alt="line"></h1>
<p class="logout_btn">Back</p>
<?php
$tbl="users";
$sql = "SELECT * FROM users";
$result = mysql_query($sql, $connect);
while($rows = mysql_fetch_array($result)){
echo $rows['user_name'];
echo ' ';
echo $rows['user_id']
?>
delete
<?php
} mysql_close();
?>
<script>
function alertFunction()
{
var r=confirm("Do you want to delete this user?");
if (r==true)
{
}
else
{
return (false);
}
}
</script>
</div><!--cms_container-->
</body>
</html>
I would just like the alert function to stop then process of deleting the content when i press cancel.
Change:
onClick="alertFunction()"
to:
onClick="return alertFunction()"
and in the function itself, change the false return to return false;. BTW, since a confirm returns true/false, you can change the first part of the condition to if (r)
Related
Good Day!
I'd like to ask something. I have a link named "delete" at the index file. Now, I want to confirm from a user before doing the delete operation. However, I'd like to put the script for confirmation to the delete file. I've tried multiple ways, yet it's useless. But it can delete actually, my problem exactly is that, the confirmation box does not prompt. Kinda' stock in here. Please help.
Heres my code at index.php (link to delete):
`<p><strong>Country: </strong> <?php echo $country['countries'];?>   |
  Edit |
<a href="deletecountry.php?id=<?php echo $country['id']; ?>"
class="confirmation">Delete</a></p>`
And here's my delete.php file:
`<?php
require 'dbconnect.php';
$id = $_GET['id']; ?>
<script>
function confirmationDelete(){
var conf = confirm('Are you sure want to delete this record?');
if(conf==true){
<?php
$sql = "DELETE countries FROM countries WHERE id=$id";
if (mysqli_query($connect, $sql)) { ?>
alert("Record Deleted!");
<?php }
else { ?>
alert("Error Deleting Record!");
<?php } ?>
}
return conf;
}
</script>`
in
Delete
then in your deletecountry.php
<?php
session_start();
require 'dbconnect.php';
$id = $_GET['id']; ?>
$sql = "DELETE countries FROM countries WHERE id=$id";
if (mysqli_query($connect, $sql)) {
$_SESSION['msg'] = 'Successfully Deleted';
}
else {
$_SESSION['msg'] = 'Error Deleting';
}
// redirect to somewhereelse.php
then in your somewhereelse.php
<?php
session_start();
if(isset($_SESSION['msg']))
{
echo '<script>alert("'. $_SESSION['msg'] .'")</script>';
session_unset('msg');
}
?>
<a onclick='javascript:confirmationDelete($(this));return false;' href="delete.php?id=1">Delete</a>
and create javascript function
function confirmationDelete(anchor)
{
var conf = confirm('Are you sure want to delete this record?');
if(conf)
window.location=anchor.attr("href");
}
or
delete
I am using Googles reCaptcha API for form validation.
I have opted to have the submit button show once the validation has been complete by using a little bit of JS.
<?php
if(isset($_POST['Login'])){
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = '6LerNA0UAAAAAEReb9rS5JXjtvNSYlMjKiocUv_O';
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
if(isset($data->success) AND $data->success==true){
//show submit button
echo '<script type=\"text/javascript\">
function myFunction() {
document.getElementById("logDiv").style.visibility="visible";
}
</script>';
}
else{ // stay hidden
'<script type=\"text/javascript\">
function myFunction() {
document.getElementById("logDiv").style.visibility="hidden";
}
</script>';
}
}
?>
<div id='logDiv' style='visibility:hidden')
<?php
echo $form->add('Login',array('type' => 'submit'));
?>
</div>
Currently, the solution isn't working; when the Captcha is validated the div remains hidden.
Is this a result of a syntax error or have a made a logical error?
What is the bug in my code?
Are there any more robust solutions?
Why not simply use a php condition to show the div? I think your JS isnĀ“t working because you never call myFunction().
Try something like this but it will become complex over time and amount of code:
if(isset($data->success) AND $data->success==true){
$showButton = true;
}
......
if($showButton) { ?>
<div id='logDiv' style='visibility:hidden'
<?php echo $form->add('Login',array('type' => 'submit'));
?> </div> <?php }
......
Or a simple Solution:
if(is_bool($data -> success) && $data -> success){
echo '<div id="logDiv">'.$form->add('Login',array('type' => 'submit')).'</div>';
}
Echo the HTML Elements only if validition was successful otherwise simply dont ouput any HTML for the Div.
Hope this Helps.
I've written a simple login script that connects to a db, and now I want to insert a paragraph with jQuery in my #loginbox which says 'Login failed' when
if (!$row = mysqli_fetch_assoc($result))
is true.
My thought was:
[function.js]
function loginfailed() {
$('#loginbox').html("<p>Login failed.</p>");
}
[login.php]
<head>
<script type="text/javascript" src="functions.js"></script>
</head>
<?php
include '../config.php';
include 'dbh.php';
session_start();
$uid = $_POST['uid'];
$pw = $_POST['pw'];
$sql = "SELECT * FROM user WHERE uid='$uid' AND pw='$pw'";
$result = mysqli_query($conn, $sql);
if (!$row = mysqli_fetch_assoc($result))
{
header('Location: ../index.php');
echo '<script> loginfailed(); </script>';
}
else
{
header('Location: ../index.php');
}
?>
But it doesn't work.
DON'T EVER STORE PASSWORDS IN PLAIN TEXT!!
Regarding your question.
The header function redirects to index.php and does not execute the echo. One solution can be to add a $_GET parameter and after the redirect check if it exists and echo the message or append it with JS.
if (!$row = mysqli_fetch_assoc($result))
{
header('Location: ../index.php?status=fail');
}
In the index.php file at the bottom (if you want to use JS/jQuery to show message)
<script>
var status = "<?php echo (!empty($_GET['status']) && $_GET['status'] === 'fail') ? 0 : 1; ?>";
if(!status) loginfailed();
</script>
Thanks guys, but i've found my own solution with the help of Allkin.
My header now redirects to
header('Location: ../index.php?status=fail');
and my #loginbox checks if status is set and then executes my loginfailed() function.
if(isset($_GET['status'])) {
echo '<script> loginfailed(); </script>';
}
Nothing easy like that!
Thanks for your help everyone.
I want to show JavaScript alert after successful data insertion in MySQL. How to do this? I have written this code but it shows JavaScript alert everytime I open this page and as soon as i click on OK of JavaScript alert it redirects me to finalmem.php, without the action of taking values from users!
$sql="INSERT INTO members VALUES ('$name', '$email', '$ybr', '$ach')";
if(!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
else
{
echo '<script language="javascript">';
echo 'alert("Successfully Registered"); location.href="finalmem.php"';
echo '</script>';
}
Thanks in advance.
Use is set isset($_POST['submit']) to check whether user submits the form or not
<?php
include 'SQLIDB.php';
if(isset($_POST['submit'])){
$name=$_POST['name'];
$email=$_POST['email'];
$ybr=$_POST['ybr'];
$ach=$_POST['ach'];
$sql="INSERT INTO members VALUES ('$name', '$email', '$ybr', '$ach')";
if(!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
else
{
echo '<script language="javascript">';
echo 'alert("Successfully Registered"); location.href="finalmem.php"';
echo '</script>';
}
}
?>
<form action="" method="post">
<input type="text" name="name">
<input type="text" name="email">
<input type="text" name="ybr">
<input type="text" name="ach">
<input type="submit" name="submit" value="Submit">
</form>
You need to know two things, one of them it's to confirm if your data it's saved succefully.
For this you can play with
mysql_affected_rows()
and this function will return the number of rows affected by your query. If zero, it was not inserted. If >= 1, it was.
So:
if ( mysql_affected_rows() >= 1 ){ /* inserted! now do something... */ }
If you are using an auto-incrementing column for row ID, you can use mysql_insert_id() as well:
if ( mysql_insert_id() > 0 ) { /* inserted! now do something... */ }
Then you can work with jQuery UI for show a dialog like this:
[https://jqueryui.com/dialog/][1]
You need tot load the .css and .js files to run jQuery and inside your code put this:
<script>
$(function() {
$( "#dialog" ).dialog();
});
</script>
And this in your view:
<div id="dialog" title="Basic dialog">
<p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>
Normally this it's super ugly to do for me, because the best way it's doing this by AJAX.
You can try like this
<?php session_start();
//Include database detail here
if(isset($_POST['name'])){
$name = mysqli_real_escape_string($_POST["name"]);
$ybr = mysqli_real_escape_string($_POST["ybr"]);
email = mysqli_real_escape_string($_POST["email"]);
$ach = mysqli_real_escape_string($_POST["ach"]);
//Do your data validation here
$_SESSION['sname'] = $name;
$_SESSION['sybr'] = $ybr;
$_SESSION['semail'] = email;
$_SESSION['sach']= $ach;
$sql="INSERT INTO members VALUES ('$name', '$email', '$ybr', '$ach')";
if(!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
} else {
echo '<script language="javascript">';
echo 'alert("Successfully Registered"); location.href="finalmem.php"';
echo '</script>';
}
}
?>
Good day. my problem is, the javascript alert doesn't work on else statement. In my else statement i want to show a javacript alert that the registration was succesful, but it doesn't appear.. here's my code
<?php
if(isset($_POST['potpot'])){
$file=$_FILES['image']['tmp_name'];
$image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name= addslashes($_FILES['image'] ['name']);
$image_size= getimagesize($_FILES['image'] ['tmp_name']);
if ($image_size==FALSE) { ?>
<script type='text/javascript'>alert('Oppss! Thats not an image!')</script>
<?php
}else{ ?>
<script type='text/javascript'>alert('Wait for admin confirmation! Check your email within 24 hours')</script>
<?php
move_uploaded_file($_FILES["image"] ["tmp_name"], "images/" . $_FILES["image"]["name"]);
$fullname= $_POST['name'];
$course=$_POST['course'];
$yeargrad=$_POST['year'];
$img=$_FILES['image']["name"];
$email=$_POST['email'];
mysql_query("INSERT INTO tblreg(fullname,course,
year_grad,img,email,username,password,status)
VALUES('$fullname',
'$course', '$yeargrad','$img', '$email', 'no', 'no', 'not')");
header('location:reg.php');
}
}
?>
alert does not appear because of redirect (header('location:reg.php'))