Modal not showing up after login in php - javascript

My modal is not showing up after I add header(location: homepage.php) but modal is working fine if I remove the header. How can I possibly do it? I've also tried using echo for alert and same thing happens, so I don't know what is wrong with my code. I hope someone can help me thank you!. Here is my code
login.php
if(isset($_POST['submit']))
{
$email = $_POST['email'];
$password = $_POST['password'];
$object = new Login();
$object->getCredentials($email, $password);
}
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST">
<div>
<label><b>EMAIL ADDRESS</b></label>
<input type="email" name="email" placeholder="Email"></input>
</div>
<div>
<label><b>PASSWORD</b></label>
<input type="password" name="password" placeholder="Password"></input>
</div>
<button type="submit" id="submit" name="submit">Login</button>
</form>
processlogin.php
<?php
include_once 'db.php';
class Login
{
public function getCredentials($email, $password)
{
$email = $email;
$password = $password;
$object = new Db();
$stmt = $object->connect()->prepare("SELECT * FROM user WHERE email=?");
$stmt->execute([$email]);
$stmtFetch = $stmt->fetch();
if($stmt->rowCount()==1 && $stmtFetch['email'] == $email && $stmtFetch['password'] == $password)
{
echo "<script>$('#loginsuccess').modal('show')</script>";
header("location: homepage.php");
}
}
}

I found something that might interest you here:
Interview Question: Can we have an echo before header?
The problem is that we cannot send the header after we start sending the output, and if you send the header before the echo, the echo will not be executed.
Try this:
Solution 1: (from the link above).
ob_start();
echo "<script>$('#loginsuccess').modal('show')</script>";
header("location: homepage.php");
ob_end_flush();
Solution 2: Use a javascript redirection instead of header function.
echo "<script>
$('#loginsuccess').modal('show');
window.location.replace('http://fullpath-homepage.php');
</script>";
Additional note:
You can use also:
window.location.href="http://example.com";
window.location.assign("http://example.com");
The replace method navigates to the URL without adding a new record to the history.

UPDATE: FOUND THE ANSWER
I use Yeti82's answer and this is what I did to make the delay to show modal of success and then directing to the next page.
echo "<script>
$('#loginsuccess').modal('show');
setTimeout(function() {window.location.href=\"homepage.php\";}, 1000);
</script>";

Related

How to call and display a database in phpMyAdmin

My assignment is to create two tables in phpMyAdmin, and then to create a simple form where the user can click a button and have the two tables displayed. I have the landing page for the assignment finished with header and search bar and button, but I'm having trouble figuring out how to bring the two tables in from the database and display them once the button is clicked.
I have had a tutor help with some of the code but I haven't been able to get it to work properly and would love any further help.
Here is the code I have now (the two separate php code chunks are two ways people tried to help me do it but I don't know which works or how to implement it):
<!DOCTYPE html>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {die("Connection Failed: " . $conn->connect_error);
}
echo "Connected Successfully";
?>
<html>
<head>
</head>
<body>
<h1>Health Club Patron and Class Information</h1>
<form name="contact-form" action="" method="post" id="contact-form">
<div class="form-group">
<label for="Search">Search</label>
<input type="text" class="form-control" search="your_name" placeholder="Search" required>
</div>
<button type="print" class="btn btn-primary" name="print" value="Print" id="submit_form">Print</button>
</form>
</body>
</html>
$connection = mysql_connect('localhost', 'root', ''); //The Blank string is the password
mysql_select_db('hrmwaitrose');
$query = "SELECT * FROM employee"; //You don't need a ; like you do in SQL
$result = mysql_query($query);
echo "<table>"; // start a table tag in the HTML
while($row = mysql_fetch_array($result)){ //Creates a loop to loop through results
echo "<tr><td>" . $row['name'] . "</td><td>" . $row['age'] . "</td></tr>"; //$row['index'] the index here is a field name
}
echo "</table>"; //Close the table in HTML
mysql_close(); //Make sure to close out the database connection
Try looking at examples on this website, good example's taken from W3 schools to learn with some simple examples.
https://www.w3schools.com/php/php_mysql_select.asp
And a form handling example in PHP https://www.w3schools.com/php/php_forms.asp
You setup a php file such as post.php then your form will post to that endpoint. Or if you are posting a PHP form to itself you use <?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?> for the post address in the form. When learning, try taking these simpler like the example's below than building from that, so you get the basic idea.
Here's a few examples, this one just grabs the rows from the database.
<?php
$servername = "localhost"; // Server host
$username = "username"; // Database username
$password = "password"; // Database password
$dbname = "hrmwaitrose"; // Your database name
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Select the rows name and age from employee
$sql = "SELECT name, age FROM employee";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo " - Name: " . $row["name"]. " " . $row["age"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Simple example post a form to PHP file a different URL, not posting to itself.
Filename: index.php
<html>
<body>
<form action="results.php" method="get">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="age"><br>
<input type="submit">
</form>
</body>
</html>
Then your results.php contains
Filename: results.php
<html>
<body>
Welcome <?php echo $_GET["name"]; ?><br>
Your email address is: <?php echo $_GET["age"]; ?>
</body>
</html>
This is an example using a form posting to itself, instead of the example's above which post to another file. Using $_GET["name"] you are grabbing the post variable's from the URL and then you can query your database, unless you are using _POST. If your posting directly to the same file you would do something like this, which I think your question is asking.
<?php if (!empty($_POST)): ?>
Welcome, <?php echo htmlspecialchars($_POST["name"]); ?>!<br>
Your age is <?php echo htmlspecialchars($_POST["age"]); ?>.<br>
<?php else: ?>
<form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?> method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="age"><br>
<input type="submit">
</form>
<?php endif; ?>

PHP in JavaScript brokes all scripts

When I'm using PHP in JavaScript, then all scripts don't work...
Even if I use php in comment.
<script>
//var variable = <?php echo json_encode($_SESSION['abc']); ?>;
</script>
This comment above destroy all scripts in <script></script> tags.
When I'll delete this line with the comment, then every script will work.
The same thing is when I just want to use PHP in JavaScript (without comment).
Could You help me ?
Here is code which was cut by me (to give You only necessary part of code), please help :) :
<?php
session_start();
if (isset($_POST['login']) && isset($_POST['password']) && isset($_POST['email']))
{
$validation = true;
$firstName = $_SESSION['firstName'];
$lastName = $_SESSION['lastName'];
$street = $_SESSION['street'];
$phone = $_SESSION['phone'];
$login = $_POST['login'];
$password = $_POST['password'];
$email = $_POST['email'];
require_once "connect.php";
mysqli_report(MYSQLI_REPORT_STRICT);
try
{
$connection = new mysqli($host, $db_user, $db_password, $db_name);
if($connection->connect_errno!=0)
{
throw new Exception(mysqli_connect_errno());
}
else
{
if ($validation == true) // when validation process will be successfuly done - i cut validation process
{
if($connection->query("INSERT INTO users values (NULL, '$firstName', '$lastName', '$street', '$phone', '$login', '$password', '$email')"))
{
$_SESSION['abc'] = "done";
//here is also header(location) to login page
}
else
{
throw new Exception($connection->error);
}
}
$connection->close();
}
}
catch(Exception $e)
{
echo '<div class="error">error. sorry, please to register in other term</div>';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<script>
//there are other functions for local/session storage
function deleteSessionData()
{
var variable = "<?php echo $_SESSION['abc']; ?>";
if(variable == "done")
{
sessionStorage.removeItem('firstName');
sessionStorage.removeItem('lastName');
sessionStorage.removeItem('street');
sessionStorage.removeItem('phone');
sessionStorage.removeItem('login');
sessionStorage.removeItem('password');
sessionStorage.removeItem('email');
}
}
</script>
</head>
<body>
<form id="myForm" method="post">
<label for="login">Login: </label>
<input type="text" id="login" name="login">
<label for="password">Password: </label>
<input type="text" id="password" name="password">
<label for="email">E-mail:</label>
<input type="email" id="email" name="email">
<button onclick="java script: document.getElementById('myForm').submit();deleteSessionData();">Register</button>
</form>
</div>
</body>
</html>
you need to comment the php too
//var variable = <?php // echo json_encode($_SESSION['abc']); ?>;
I wouldn't inject PHP into javascript like this without sanitation though.

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.

PHP contact form modification [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
i've got a basic php script for simple contact form with name, email and message inputs.
I wish to include few more options in it but don't know how to. I've searched but couldn't find all in one solution for. I would like to:
1. Send a copy to senders email
I would like to include input for sender to have an option to receive a copy of he's submit to he's email if he checkes that input in the form.
2. Upload a file
Also if possible in the same php script i wish to give a possibility for the sender to attach a file (preferably img extensions only) when submiting a form.
3. Thank you message
Not sure about this, but now i have a simple thank you message in echo when form is submited. If possible, i wish for this message to stay visible for 5 seconds then redirect to index.html.
Here is php for the form:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent="Name: $name \nEmail: $email \nMessage: $message";
$recipient = "test123#...";
$subject = "Contact";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo
"<div style='display: block; text-align: center;'>" .
"<span style='font-size: 14px;'>You message has been sent!</span>" .
"<a href='index.html'>Go back</a>" .
"</div>";
?>
and demo jsfiddle of the form setup.
Thanks for any help.
This is a global setup just to let you know how I would do this (if I wanted to do this on 1 page, but it's better to make functions, etc.)
EDIT: Please note also that I don't know if this works. Maybe there are errors but I have done this just to get you started.
<?php
//Check if form submitted
if (isset($_POST)) {
//this all will run when form is submitted
//First sanitize you data thats been posted
$name = htmlentities($_POST['name'], ENT_QUOTES, 'UTF-8');
$email = htmlentities($_POST['email'], ENT_QUOTES, 'UTF-8');
$message = htmlentities($_POST['message'], ENT_QUOTES, 'UTF-8');
//make a error array to hold errors
$error = array();
//check if fields are not empty you can also do other checks
if (!empty($name) || !empty($email) || !empty($message))
//here you could do extra checks.. like check if emai is really a email...
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
//email invalid
array_push($error, 'email not valid');
}
//for image you could also do a if...
if(isset($_FILES)) {
$uploads_dir = 'YOUR DIR'
$name = $_FILES['image']['name'];
$type = $_FILES['image']['type'];
$size = $_FILES['image']['size'];
$temp = $_FILES['image']['tmp_name'];
$error = $_FILES['image']['error'];
if ($error === 4) {
//No file was selected
return false;
}
else
{
//do your stuff with the image here...
move_uploaded_file($temp, "$uploads_dir/$temp");
}
///you could do more ifs.. but if all is good then do the mail
$subject = 'new contact form message';
$headers = 'From: webmaster#example.com' . "\r\n" .
'Reply-To: webmaster#example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($email, $subject, $message, $headers);
$success = "here the success message";
} else {
//some fields are empty
array_push($error, 'some fields are empty');
}
?>
<!-- THE ENCTYPE IS NEEDED FOR IMAGES -->
<form action="submit.php" name="contact-form" id="contact-form" method="post" enctype="multipart/form-data">
<input name="name" placeholder="Name" type="text" id="name" required />
<input name="email" placeholder="Email" type="email" id="email" required />
<textarea name="message" placeholder="Message" id="message" required></textarea>
<input type="file" id="upload-file" accept="image/*" />
<div class="clear"></div>
<input type="checkbox" id="copy" name="copy" />
<label for="copy">Send a copy to my email</label>
<div class="clear"></div>
<input type="submit" value="Submit" form="contact-form" name="submit-form" />
</form>
<?php
if (isset($success) && !empty($success)) {
//echo the success
echo $success
}
if (isset($error) && !empty($error)) {
//loop trough error
foreach ($error as $e) {
echo $e;
}
}
?>

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