Showing success message on a redirected page - javascript

There's two pages: one is index.php and another is add-name.php . add-name.php has a form which takes a name and after a successful submission, it redirects to index.php page where all the names is shown.
I was wondering how can I show a message that the name has been added on index.php page after add-name.php page redirects to index.php page when it's submitted.
add-name.php
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST"){
$name = $_POST["name"];
addName($name); // this addName function saves the name to a
file called names.txt and index.php page
uses this file to access all the names
header("Location: index.php");
}
?>
<form action="add-name.php" method="POST">
<label for="name">Name:</label>
<input type="text" name="name" id="name">
<input type="submit" name="submitButton" value="Save">
</form>

Use session
add-name.php
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST"){
$name = $_POST["name"];
// addName($name);
session_start();
$_SESSION["name"] = "added";
header("Location: index.php");
exit();
}
?>
<form action="add-name.php" method="POST">
<label for="name">Name:</label>
<input type="text" name="name" id="name">
<input type="submit" name="submitButton" value="Save">
</form>
index.php
<?php
session_start();
if (isset($_SESSION["name"]) && $_SESSION["name"] === "added") {
echo "name added";
unset($_SESSION["name"]);
} else {
echo "just called";
}
# ...

Related

How to give action on php pages

I have made two pages. I have used php form validation in my first page, i.e., form.php and I have to give action on second page i.e., data_ins.php. Please let me know how will it possible with my coding.
Here are my pages:
form.php
<?php $fnameErr = $lnameErr = "";
$fname = $lname= ""; if($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST['fname']))
{
$fnameErr = "First Name is required";
}
else
{
$fname= formVal($_POST['fname']);
}
if(empty($_POST['lname']))
{
$lnameErr = "Last Name is required";
}
else
{
$lname= formVal($_POST['lname']);
} }
function formVal($data)
{
$data = trim($data);
$data = stripcslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?> <!DOCTYPE html> <html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
First Name:
<input type="text" name="fname"> <span style="color:red;"><?php echo $fnameErr ?></span> <br>
Last Name:
<input type="text" name="lname"> <span style="color:red;"><?php echo $lnameErr ?></span> <br>
<input type="submit" name="submit">
</form>
</body> </html>
data_ins.php
<?php $conn = mysqli_connect("localhost","root","","test_db");
$sql = "insert into records (FirstName, LastName) values ('$fname', $lname)";
if($result=mysqli_query($conn, $sql))
{
echo "Data Inserted Successfull";
}
else
{
echo "Invalid";
}
mysqli_error($conn); ?>
Personally, I think you may of made it harder than you needed to.
Here is what I'd do with the PHP side:
if (isset($_POST['submit']))
{
if (!empty($_POST['fname']))
{
if (!empty($_POST['lname']))
{
// Add Database insert code here..
} else {
echo "Last name is required";
}
} else {
echo "First name is required";
}
}
As for the form, you don't need to add the PHP self (just add the method) like so:
<form method="POST" action="">
First Name: <input type="text" name="fname"><br>
Last Name: <input type="text" name="lname"><br>
<input type="submit" name="submit">
</form>
Hope this helps more so than your initial idea of doing it.
PLEASE NOTE: I haven't added the $data trim etc in but you'd add these in firstly where // do code note is.
1.change your form like this
`<form method="POST" action="location of your data_ins.php">`
2.in your data_ins.php must have database config code or include it.
3.get your all form value in data_ins.php pass to insert query
<form method="POST" action="">
First Name: <input type="text" name="fname"><br>
Last Name: <input type="text" name="lname"><br>
<input type="submit" name="submit">
</form>
Besides your code, your method (as question is not about it).
To execute other .php file you can use PHP statements:
require
include
include_once
In your case require should be the one to use, like: require 'data_ins.php'; after validation.

403 Forbidden error in PHP Login

Whenever I click the submit button of my login, I'm taken to a blank page which has the texts "403 Forbidden", I feel that this may be due to the URL of my login page as it is "mywebsite.com8:8888/login/" and is hosted on a different port (I'm using Tornado web server).
HTML
<form method="POST">
<fieldset id="inputs">
<input name="username" id="username" required>
<input name="password" id="password" type="password" name="Password" placeholder="Password" required>
</fieldset>
<fieldset id="actions">
<input type="submit" id="submit" value="Log in" name="submit">
<label><input type="checkbox" checked="checked"> Keep me signed in</label>
</fieldset>
</form> <div id="container"></div>
PHP
<?php header('Access-Control-Allow-Origin: *'); ?>
<?php
if (isset($_POST['submit'])){
session_start();
error_reporting(0);
$username = $_POST['username'];
$password = md5($_POST['password']);
$connection = mysql_connect("localhost", "moot", "lmlkmklmklmkl"); // Establishing Connection with Server
$db = mysql_select_db("snamr", $connection); // Selecting Database from Server
$sql="SELECT * FROM accs WHERE name='$username' and password='$password'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
$check = mysql_query("SELECT active FROM accs WHERE name = '$username'");
while($rows=mysql_fetch_assoc($check)){
$active = $rows['active'];
}
// If result matched $myusername and $mypassword, table row must be 1 row
if($count!=1){
echo "Wrong Username or Password";
}
elseif ($active == 0) {
echo "Your account isn't active!";
}
else {
$_SESSION['username'] = $username;
}
$time = time();
$setLogged= mysql_query("UPDATE accs SET loginstatus = '$time' WHERE name = '$username'") or die(mysql_error());
}
}
?>
JAVASCRIPT WHICH LOADS THE PHP INTO HTML (good reasons for this)
<script type="text/javascript">
$(document).ready(function(){
$("#container").load('http://mywebsite.com/sname/signing.php');
});
</script>
The login form along with the PHP works with all other files on my default port but when I take the code to my files hosted on port 8888 things go wrong. Hence why I think the main issue may be in the domain.
Any solutions?

Send PHP errors back to index

So I have an index.php and a r.php. R.php is the registration part. And index.php is the actual form. My question is how can I have errors from r.php be send back to index.php if they exist. So instead of displaying errors on r.php I want them on index.php and prevent the form from advancing.
Here's the index.php
<!DOCTYPE html>
<html>
<body>
<form method="post" action="r.php">
<input type="text" name="name" placeholder="Name">
<input type="submit">
</form>
</body>
Its all very simple. Now here's r.php
<?php
$name = $_POST['name'];
if ($name < 3){
//display error
}
else {
//proceed
}
?>
Should I do this with JS? Or this there a better way.
One way is to use sessions:
<?php session_start(); ?>
<!DOCTYPE html>
<html>
<body>
<?php echo isset($_SESSION['message']) ? $_SESSION['message'] : ''; ?>
<form method="post" action="r.php">
<input type="text" name="name" placeholder="Name">
<input type="submit">
</form>
</body>
<?php
session_start();
unset($_SESSION['message']);
$name = $_POST['name'];
if ($name < 3){ // you probably want strlen($name) < 3
$_SESSION['message'] = 'error';
header('Location: index.php');
exit;
}
else {
//proceed
}
?>
Other than sessions you could redirect back with a query string and use that:
header('Location: index.php?message=' . urlencode('some kind of error');
Then:
<?php echo isset($_GET['message']) ? $_GET['message'] : ''; ?>
Using a single script for this would be easier, just put this all in one file, and check to see if the form has been submitted. If the form has been submitted, you an just include the variables you want straight away.
This is pretty crude, but it gives you an idea of where you can go with this:
<?php
if (isset($_POST['name'])) {
// Begin processing form stuff
$name = $_POST['name'];
// Initialise error variable
$error = null;
if ($name < 3) {
// Display error, for example:
$error = 'Name is less than 3';
} else {
// Proceed
}
}
?>
<!DOCTYPE html>
<html>
<body>
<?php if ( ! empty($error)) { ?>
<p><?php echo $error; ?></p>
<?php } ?>
<form method="post" action="r.php">
<input type="text" name="name" placeholder="Name">
<input type="submit">
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<?php
$msg = '';
if(isset($_GET['e'])
{
$msg = "Error! Input not valid.";
}
?>
<body>
<?php
if($msg!='')
{
echo "<font color='red'>".$msg."</font>";
}
?>
<form method="post" action="r.php">
<input type="text" name="name" placeholder="Name">
<input type="submit">
</form>
</body>
Just pass a variable e using GET request to the index page if an error is found.
<?php
$name = $_POST['name'];
if ($name < 3){
header("Location: index.php?e=error");
}
else {
//proceed
}
?>
GET request will send the variable e using the URL, and if e is found to be having a value, it means there was an error in r.php
Use javascript for simple form validation. In case you require some security stuff or db stuff, you can use session/cookie or use header function to go back.

How to get a msgbox?

I am creating a simple enquiry form with upload option.
If I click submit button it goes to another page and displays success message but it should come in the same page as a message box. What should I do?
Here is my Html code:
<ul>
<li><span>Name</span>
<input name="name" type="text" size="25" class="text1" />
</li>
<li><span>Contact</span>
<input name="contact" type="text" size="25" class="text2" />
</li>
<li><span>E-mail</span>
<input name="email" type="text" size="25" class="text3" />
</li>
<li><span>Subject</span>
<input name="subject" type="text" size="25" class="text4" />
</li>
<li><span>Message</span>
<textarea name="message" size="250" class="text5"></textarea>
</li>
</ul>
<label for="upload"></label>
<div class="x">
<input type="file" name="upload" id="file" class="button">
</div>
<div class="x1">
<input type="submit" name="submit" value="Submit" class="button" />
</div>
And this is my PHP code for uploading and inserting:
<?php
$target = "upload/";
$target = $target . basename($_FILES['upload']['name']);
$ok = 1;
if (move_uploaded_file($_FILES['upload']['tmp_name'], $target))
{
echo "The file " . basename($_FILES['upload']['name']) . " has been uploaded";
}
else
{
echo "Sorry, there was a problem uploading your file.";
}
?>
<?php
include ("conn.php");
if (isset($_POST['submit']))
{
$sql="insert into cform (name,contact,email,subject,message,upload)values('".$_POST['name']."','".$_POST['contact']."','".$_ POST['email']."','".$_POST['subject']."','".$_POST['message']."','$target')";
$result=mysql_query($sql);
if (!$result)
{
echo "could not enter data";
}
else
{
echo "successfuly entered";
}
}
?>
This PHP page has to run in background and when I click the submit button a message box should display success.
Edit the echo portion of the page as
second page
$rspnse = "";
if(!$result){
$rspnse = "Error";
}
else{
$rspnse = "Success";
}
header('Location: previous_page.php?response='.$rspnse);
Replace the previous_page.php with your original url of the first page
first page
<?php
if(isset($_GET['response'])){
?>
<script>
alert('<?php echo $_GET['response'] ?>');
</script>
<?php
}
?>
Hope this helps...
if(! $result) {
$msg = "could not enter data";
}else{
$msg = "successfuly entered";
}
header('Location: http://www.example.com/form.php?message=$msg');
//Redirect to form page with set message.
add script in form page to display message
if(isset($_GET['message'])){
print $_GET['message'];
}
This solution for as per your code
And another option is using ajax.

Redirect happens before form data is processed

What i'm trying to do here is to sends an email to a salesperson notifying them that their client has viewed a google docs presentation.
The query's Num=val is a serial number that I use to get the actual google doc's url out of a database and stuff it into a form.
My problem is that the page redirects before the data is retrieved, and ends up going to the default for the site, nitrofill.com.index
The gdform.php file has the header redirect, which works fine if I don't try to process the form when the page loads. Heres the code:
<?php
$sn=$_GET['num'];
echo $sn;
mysql_connect($hostname,$username, $password) OR DIE ('Unable to connect to database! Please try again later.');
mysql_select_db($dbname);
$selectSQL = "select * from `Presentations` where `serialnum` ='" . $sn ."'" ;
$result = mysql_query($selectSQL) or die(mysql_error());
$row = mysql_fetch_array($result, MYSQL_BOTH);
?>
<script type="text/javascript">
function myfunc () {
var frm = document.getElementById("notice");
frm.submit();
}
window.onload = myfunc;
</script>
<title>Nitrofill Document</title></head>
<body>
<form id="notice" action="http://m3sglobal.com/gdform.php" method="post">
<input type="hidden" name="subject" value="<?php echo (urldecode($row['recipient'])) . " has viewed the document you sent them."; ?>" />
<input type="hidden" name="redirect" value="<?php echo ((urldecode($row['docurl']))); ?>"/>
<label>Email:</label><input type="text" name="email" value="<?php echo (urldecode($row['tracker'])); ?>"/>
<label>Comments:</label><textarea name="comments" cols="40" rows="5">
Document Viewed:<?php echo ((urldecode($row['docurl']))); ?>
When Accessed:<?php echo ((urldecode($row['last_accessed']))); ?>
</textarea>
<input type="submit" name="submit"/>
</form>
The gdform.php does the redirect like this:
while (list ($key, $val) = each ($query_vars)) {
fputs($fp,"<GDFORM_VARIABLE NAME=$key START>\n");
fputs($fp,"$val\n");
fputs($fp,"<GDFORM_VARIABLE NAME=$key END>\n");
if ($key == "redirect") { $landing_page = $val;}
}
fclose($fp);
if ($landing_page != ""){
header("Location: " . $landing_page);
} else {
header("Location: http://".$_SERVER["HTTP_HOST"]."/");
}
Thanks for looking!
Code in HTML is executed top-down. You're submitting as soon as you get to that block of JavaScript, which is before you even render the form on the page.
Move your JS code to the bottom of the page, or execute it after the DOM is ready.

Categories

Resources