I know this question is very common, I have search alot, and after alot of hard work, I am asking here.
I simply want to show an alert box and redirect it to a page.
The code below is redirecting me, but not showing me the alert box.
Please, let me know my mistake.
<?php
require_once('connection.php');
if(isset($_POST['person'])){ $name = $_POST['person']; }
if(isset($_POST['pwd'])){ $password = $_POST['pwd']; }
if(isset($_POST['position'])){ $pos = $_POST['position']; }
if(empty($name) or empty($password))
{
echo "<SCRIPT type='text/javascript'>
alert('Places should not be empty! Press Ok and try again!');
window.location.replace(\"addmember.php\");
</SCRIPT>";
}
else
{
//$query=mysqli_query($con,"insert into members (username, password,position) values ('$name','$password','$pos')");
echo "<SCRIPT type='text/javascript'>
alert('Added!');
window.location.replace(\"addmember.php\");
</SCRIPT>";
}
?>
I personally make this function to show an alert box and redirect it to a page.
function do_alert($msg,$link=NULL)
{
echo '<script type="text/javascript">
alert("' . $msg . '");
</script>';
if(!empty($link)) {
echo '<script type="text/javascript">
window.location="'.$link.'";
</script>';
}
}
Use this function both alert and redirect to a page use this
do_alert("Message","URL");
do_alert("Here this is your alert","addmember.php");
do_alert("Only your alert");
If the function 2nd parameter URL is empty then it'll only do alert.
try to change
window.location.replace(\"addmember.php\");
to
window.location='addmember.php';
Related
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'm using insert.php file to connect to the db, insert the user's request, send a success confirmation message then redirect user to the same page. This is the code:
if (!mysqli_query ($db_conx, $sql)) {
die ('Error: ' . mysqli_error($db_conx));
}
else {
echo '<script type="text/javascript">';
echo 'alert("Thank you! Your request has been successfully sent.")';
echo '</script>';
}
header ('Location:http://www.mywebsite.com.au/page1.php');
mysqli_close ($db_conx);
The problem is that after the user clicks on "OK" on the confirmation alert box the page moves from page1 to insert.php with a blank white screen.
I want to refresh the page1 page and stay on it.
if (!mysqli_query ($db_conx, $sql)) {
die ('Error: ' . mysqli_error($db_conx));
}
else {
echo '<script type="text/javascript">';
echo 'alert("Thank you! Your request has been successfully sent.")';
echo 'window.location.href = "http://www.mywebsite.com.au/page1.php"';
echo '</script>';
mysqli_close ($db_conx);
}
if (!mysqli_query ($db_conx, $sql)) {
die ('Error: ' . mysqli_error($db_conx));
}
else {
echo '<script type="text/javascript">';
echo 'alert("Thank you! Your request has been successfully sent.")';
echo '</script>';
}
mysqli_close ($db_conx);
echo "<META http-equiv=\"refresh\" content=\"0;URL=page1.php\">";
I could personally never get header to work properly for me either, but meta refresh has always worked the way I needed it to.
In my snippet, I use meta refresh and tell it to wait for 0 seconds (content=\"0;) before it redirects to the page1.php page (;URL=page1.php\"), that way there it will redirect directly after the user hits "Okay" on the alert message.
Alternatively, you can put in a confirmation message that does NOT need user interaction on the insert.php page, and you can can change the redirect time to something like 2 or 3 so the user has a chance to see it.
Please use this code:
if (!mysqli_query ($db_conx, $sql)) {
die ('Error: ' . mysqli_error($db_conx));
}
else {
echo '<script type="text/javascript">';
echo 'alert("Thank you! Your request has been successfully sent.")';
echo '</script>';
}
mysqli_close ($db_conx);
// Use Location: not Location : , that means now space between Location and :(colon)
header ('Location: http://www.mywebsite.com.au/page1.php');
I want to append a PHP function that shows the user his/her IP within an inputs' placeholder. I've never seen anything like this been done before so I'd like to just see if it's possible or not.
My thoughts right now is to do something along these lines:
$('input').attr(placeholder,function(){
$('input').append('<?php $variable ?>');
});
then run the PHP code through here some how. If someone can shed some light on this I would be very grateful!
try this:
$('#inputID').attr("placeholder","<?php echo $variable; ?>");
And if you want to append to all inputs:
$(":input").attr("placeholder","<?php echo $variable; ?>");
should do the work
If you want to do it in PHP you can make a function to retrieve the IP of the user then echo the script in your page:
<?PHP
function getUserIP()
{
$client = #$_SERVER['HTTP_CLIENT_IP'];
$forward = #$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote = $_SERVER['REMOTE_ADDR'];
if(filter_var($client, FILTER_VALIDATE_IP))
{
$ip = $client;
}
elseif(filter_var($forward, FILTER_VALIDATE_IP))
{
$ip = $forward;
}
else
{
$ip = $remote;
}
return $ip;
}
echo "<script type='text/javascript'>
$('input').attr(placeholder,function(){
$('input').append('".getUserIP()."');
});
</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'))