I have this little contact form manager and it displays an error message as an array. I need that every time the error message appears, the user goes down to an anchor in my page.
The code looks like this:
$errors = array();
if (filter_var($email, FILTER_VALIDATE_EMAIL)=== false){
$errors[] = 'Invalid email';
}
if (ctype_alpha($name)===false){
$errors[] = 'Invalid name';
}
if (ctype_alpha($phone)===true){
$errors[] = 'Invalid number';
}
Besides showing the message, how can I send the user to an anchor in the site?
The only way so far I got it to work was by using:
<script>
window.location = 'sent.php';
</script>
But I can't use that everytime the user gets an error, or can I?
Somehow I couldn't use the header tag with this array because the result for the array was an empty one, so I managed to do something like this at the index where the error message was posted.
<?php
if (empty($errors)===false) {
echo'<ul>';
foreach ($errors as $error) {
echo '<li style="color:red; font-weight:bolder;
text-decoration:none;">'
,$error, '</li>';
}
echo '</ul>';
echo '</br>';
?>
<script>
window.location = '#correoA';
</script>
<?php
} ?>
So this way I get the error message and the window location
Related
I have a simple register form, my form validates but will not show error messages or validation messages
This is my form function
function validate_new_user()
{
$errors = [];
if (isset($_POST['register'])) {
$email = $_POST['email'];
$name = str_replace(" ", "", $_POST['username']);
$password = $_POST['password'];
if (empty($email)) {
$errors[] = "Email Address is required";
}
if (empty($name)) {
$errors[] = "Username is required";
}
if (strlen($password) < 5) {
$errors[] = "Password must be at least 6 characters long";
}
if (!empty($errors)) {
set_message($errors[0], WARNING);
} else if (create_new_user($email, $name, $password)) {
set_message('Please check your email for user Information.', SUCCESS);
redirect_to_url("/user/login");
}
}
}
I call my validation function in my form page
<?php validate_new_user(); ?>
so if there is an error it should set message but don't.
now if it successfully it redirects to login and sets a flash message also and I call it with
<?php display_message(); ?>
That don't display a message either
Flash message code
define('SUCCESS', 'success');
define('INFO', 'info');
define('WARNING', 'warning');
function set_message($message, $type = 'success')
{
if (!empty($_SESSION['flash_notifications'])) {
$_SESSION['flash_notifications'] = [];
}
$_SESSION['flash_notifications'][] =
$message = [
'<div class="alert . $type .">$message</div>'
];
}
function display_message()
{
if (isset($_SESSION['flash_notifications'])){
return $_SESSION['flash_notifications'];
}
}
my goal is to use one set message for all notifications with styles but I cannot get none of the messages to display
I’ll assume you’re calling session_start() at the beginning of the script.
Your usage of functions makes the problem much easier to diagnose! Sometimes, though, it helps to have a different set of eyes look at it.
Your function set_message() has a couple of errors:
The initialization of $_SESSION['flash_notifications'] should occur if it is empty, but instead you are initializing if it is not empty. Hence nothing can be added
Malformed assignment. When you are building the message array to save in $_SESSION, there is no need to reassign $message. Also, usage of single quotes does not interpret variables within the quotes, so the html snippet is not what you expect.
Corrected function:
function set_message($message, $type = 'success')
{
if (empty($_SESSION['flash_notifications'])) {
$_SESSION['flash_notifications'] = [];
}
$_SESSION['flash_notifications'][] = '<div class="alert '. $type .'">'.$message.'</div>';
}
Note, it might be more understandable to write it this way:
$_SESSION['flash_notifications'][] = <<<FLASH
<div class="alert $type'">$message</div>
FLASH;
Your function display_message() is almost correct as is, except you’re returning an array, not a string. If you’re going to print it, it must be converted into a string:
function display_message()
{
if (isset($_SESSION['flash_notifications'])){
return join('',$_SESSION['flash_notifications']);
}
}
Then when you call it in your html, use the short print tag instead of the regular <?php tag:
<!— somewhere in your view (html output) —>
<?= display_message() ?>
<!— continue html —>
I have an issue that after the "Refresh" (ctrl+r and ctrl+shift+r) , the error message "You forgot to insert an email" doesn't disappear. I don't know what is the issue. Appreciate the help in advanced.
This is a snippet from my HTML PAGE with the forms:
<?php
foreach ($error as $key => $errorvalue){
echo($errorvalue);
}
?>
My process script which I "require" in the HTML page.
$error = array();
try
{
if(empty($username)) {
$error[] = "You forgot to insert a username!";
} if(empty($email)) {
$error[] = "You forgot to insert an email!";
}
}
catch (Exception $e) {
echo 'Caught exception: '.$e->getMessage();
}
if you refresh a page after you submit a from it will keep submitting it every time you refresh the page, to prevent this you can use this javasricpt code in your html codes <head> tags
<script>
if (window.history.replaceState) {
window.history.replaceState(null, null, window.location.href);
}
</script>
you can look at this website for more information.
I want to use my webpage to recognize if a $_POST is set and the, if it is, print it in the page, so this is what I really have now:
if (isset($_POST['error'])) {
echo '<div id="error">'.$_POST['error'].'</div>';
}
But what I want is that, when an if statement that I have in the same document returns true, to send a POST request to that same file and so, show the error message with the $_POST. Is this possible or it is another easy way for doing it?
Sorry for not explaining so well, this is my code:
if (password_verify($_POST['oldpassword'], $result['password'])) {
// Upload password to database
} else {
// Set the $_POST['error'] to an error message so I can show it in the error DIV.
}
Thanks!
You can define a $message athe beginning of your page then handle the errors you want to show
$message = '';
if (password_verify($_POST['oldpassword'], $result['password'])) {
// Upload password to database
} else {
//set a proper message ID which will be handled in your DIV
$message_id = 1;
header('location: /current_path.php?message='.$message_id);
}
Now in the div you can show it as
if (!empty($_GET['message'])) {
echo '<div id="error">';
if ($_GET['message'] == 1) { echo 'First message to show.'; }
elseif ($_GET['message'] == 2) { echo 'Second message to show.'; }
echo '</div>';
}
I have a form where a user is required to enter their full name, contact number and best time to call details. I would like to validate these fields on my web form so that users cannot submit the form without those fields being filled. I have used if(empty($...)) and echoed my error message however, when i try to submit the blank form it doesn't display any of the error messages. How could i resolve this?
CODE
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . '/inc/bootstrap.php');
include("config/cn.php");
$template['template'] = "page";
if($_POST)
{
// Data pulled from input form
$full_name = $_POST['full_name'];
if (empty($_POST['full_name']))
{
// Set error and return to form
echo "Field cannot be left blank";
header('Location: /call-back-form.php');
exit;
}
$contact_number = $_POST['contact_number'];
if (empty($_POST['contact_number']))
{
// Set error and return to form
echo "Field cannot be left blank";
header('Location: /call-back-form.php');
exit;
}
$best_time_to_call = $_POST['best_time_to_call'];
if (empty($_POST['best_time_to_call']))
{
// Set error and return to form
echo "Field cannot be left blank";
header('Location: /call-back-form.php');
exit;
}
$enter_sql = "INSERT INTO contact (full_name, contact_number, best_time_to_call)
VALUES('$full_name' , '$contact_number' , '$best_time_to_call')";
/*print($enter_sql);*/
$enter_query = mysql_query($enter_sql) or die(mysql_error());
header('Location: /thankyou.php');
exit;
}
?>
Well, there is an error in logic. You are doing an echo then header. Which means it shows the message and returns them to the previous page faster than they can see the message. Is this really what you wanted to do?
You should probably either post the form to itself and just just echo without the header where you want the errors displayed, or implement javascript form validation.
Also, you could use
<?
header('Location: /call-back-form.php?message=Error');
?>
And then in call-back-form.php user
<?
echo $_GET['message'];
?>
where needed
I have a form that is positioned on the page with HTML, if the user completes the form then they are thanked with a PHP message. Because the form is positioned with <form id="formIn"> CSS the PHP text is now in the wrong position, does anyone have an idea how this can be positioned so that the PHP echo text is nest to the form?
I have tried to include the code in PHP, i.e.
<div id=\"text\">
But no joy.
Code used so far is:
<?php
echo "* - All sections must be complete"."<br><br>";
$contact_name = $_POST['contact_name'];
$contact_name_slashes = htmlentities(addslashes($contact_name));
$contact_email = $_POST['contact_email'];
$contact_email_slashes = htmlentities(addslashes($contact_email));
$contact_text = $_POST['contact_text'];
$contact_text_slashes = htmlentities(addslashes($contact_text));
if (isset ($_POST['contact_name']) && isset ($_POST['contact_email']) && isset ($_POST['contact_text']))
{
if (!empty($contact_name) && !empty($contact_email) && !empty($contact_text)){
$to = '';
$subject = "Contact Form Submitted";
$body = $contact_name."\n".$contact_text;
$headers = 'From: '.$contact_email;
if (#mail($to,$subject,$body,$headers))
{
echo "Thank you for contacting us.";
}else{
echo 'Error, please try again later';
}
echo "";
}else{
echo "All sections must be completed.";
}
A good way for doing this is to create a div for displaying messages in the form page and return back from the php script to the form page including form.html?error=email or form.html?success to the url. Then with javascript you can identify when this happens and display a message or another.
Comment if you need some code examples.
EDIT:
Imagine your php script detects that email field is not filled, so it would return to the form webpage with a variable in the url:
<?php
if(!isset($_POST["email"]){
header("location:yourformfile.html?error=email")
}
?>
Then, in your form webpage you have to add some javascript that catches that variable in the URL and displays a message in the page:
Javascript:
function GetVars(variable){
var query = window.location.search.substring(1); //Gets the part after '?'
data = query.split("="); //Separates the var from the data
if (typeof data[0] == 'undefined') {
return false; // It means there isn't variable in the url and no message has to be shown
}else{
if(data[0] != variable){
return false; // It means there isn't the var you are looking for.
}else{
return data[1]; //The function returns the data and we can display a message
}
}
}
In this method we have that data[0] is the var name and data[1] is the var data. You should implement the method like this:
if(GetVars("error") == "email"){
//display message 'email error'
}else if(GetVars("error") == "phone"){
//dislpay message 'phone error'
}else{
// Display message 'Success!' or nothing
}
Finally, for displaying the message I would recommend creating a div with HTML and CSS and animate it to appear and disappear with jQuery. Or just displaying an alert alert("Email Error");
Just create a <div> before or after your form and put IF SUBMIT condition on it.
Like,
<?php
if(isset($_POST['submit']))
{ ?>
<div>
<!-- Your HTML message -->
</div>
<?php } ?>
<form>
</form>