PHP Formdata have to be triggered with JS/JQ (?) - javascript

Is it possible to run a php file/function without entering the page?
I mean it is really disturbing if you create for example a chat app and when you submit your message the whole page get reloaded.
I've tried AJAX but didn't worked. Is it impossible to post the text of the chat_area to the PHP file?
<form action="..." method="POST">
<textarea id="chat_area" name="chat_text" cols="50" rows="1"></textarea>
<input id="chat_submit" type="submit" name="submit" value="Posten">
</form>
<?php
session_start();
include_once( "database.php" );
if( $_POST["chat_area"] ){
$name = $_SESSION["firstname"]
$time = "[" . date( "H:i", time() + 3600 ) . "]";
$message = $_POST["chat_area"]
mysql_query( "INSERT INTO chat( name, time, message ) VALUES ('$name', '$time', '$message' )" );
}
?>

It's default behaviour of the form. For chat-like app, you should use ajax. Not only for posting the form data, but also for receiving messages from backend app. Otherwise, you'll have to reload a page to check whether or not you got some new messages.
With jQuery you could use event.preventDefault() to stop the default action of the form to be triggered, and then post the data to PHP.
You should split your app to 2 files. Main page, and file, where all the data is sent to (and received from).
Your front end:
<?php
session_start();
// rest of the PHP, if any...
?>
<form method="POST">
<textarea id="chat_area" name="chat_text" cols="50" rows="1"></textarea>
<input id="chat_submit" type="submit" name="submit" value="Posten">
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$('#chat_submit').on('click', function(e){
e.preventDefault();
$.ajax({
type : "POST",
url : 'your_php_file.php',
dataType : 'text',
data :{
message : $('#chat_area').val()
},
success : function(data){
if(data == 'success'){
// E.g.: append the message to chat area after it is successfully stored in DB.
}
},
complete : function(status){
// call on complete
},
error : function(response){
// call when error
}
});
});
});
</script>
PHP (your_php_file.php):
<?php
session_start();
include_once("database.php");
if( isset($_POST["message"]) ){
$name = $_SESSION["firstname"];
$time = "[" . date( "H:i", time() + 3600 ) . "]";
// a little of safety:
$unsafe_message = trim($_POST["message"]);
$safe_message = mysql_real_escape_string($unsafe_message);
mysql_query
( "INSERT INTO chat( name, time, message )
VALUES
('$name', '$time', '$safe_message' )" ) or die('error');
echo 'success';
}else{
echo 'error';
}
?>

Related

Using preventDefault(); with a php form

I'm pretty new to programming in the middle of 2 Udemy courses. one for Javascript and one for PHP, anyways I'm not sure how to tackle this problem. On my site, if you click the Sign-Up link, the nav slides out a sign up form. the problem is if the input has an error like it's blank or something it closes the nav automatically instead of just displaying the error. so I have to click Signup again to see the error. I can't make the nav stay open. So I found a possible solution to my problem called
preventDefault(); which makes the form not reload the page finally, but it now it does not submit the data and display error messages now. My site is a WordPress site if that makes a difference. All my google answers I've looked at say preventDefault(); is the answer but if you look at this from w3schools.com.
The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur.
For example, this can be useful when:
Clicking on a "Submit" button, prevent it from submitting a form
so I'm very confused about how this function can fix my problem.
here's my code
HTML / PHP
<?php
global $wpdb, $user_ID;
//Check whether the user is already logged in
if ( !$user_ID ) {
// Default page shows register form.
// To show Login form set query variable action=login
$action = ( isset( $_GET[ 'action' ] ) ) ? $_GET[ 'action' ] : 0;
// Login Page
if ( $action === "login" ) {
?>
<?php
$login = ( isset( $_GET[ 'login' ] ) ) ? $_GET[ 'login' ] : 0;
if ( $login === "failed" ) {
echo '<div class="col-12 register-error"><strong>ERROR:</strong> Invalid username and/or password.</div>';
} elseif ( $login === "empty" ) {
echo '<div class="col-12 register-error"><strong>ERROR:</strong> Username and/or Password is empty.</div>';
} elseif ( $login === "false" ) {
echo '<div class="col-12 register-error"><strong>ERROR:</strong> You are logged out.</div>';
}
?>
<div class="col-md-5">
<?php
$args = array(
'redirect' => home_url(),
);
wp_login_form( $args );
?>
<p class="text-center"><a class="mr-2" href="<?php echo wp_registration_url(); ?>">Register Now</a> <span clas="mx-2">ยท</span><a class="ml-2" href="<?php echo wp_lostpassword_url( ); ?>" title="Lost Password">Lost Password?</a></p>
</div>
<?php
} else { // Register Page ?>
<?php
if ( $_POST ) {
$error = 0;
$username = esc_sql( $_REQUEST[ 'username' ] );
if ( empty( $username ) ) {
echo '<div class="col-12 register-error">User name should not be empty.</div>';
$error = 1;
}
$email = esc_sql( $_REQUEST[ 'email' ] );
if ( !preg_match( "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/", $email ) ) {
echo '<div class="col-12 register-error">Please enter a valid email.</div>';
$error = 1;
}
if ( $error == 0 ) {
$random_password = wp_generate_password( 12, false );
$status = wp_create_user( $username, $random_password, $email );
if ( is_wp_error( $status ) ) {
echo '<div class="col-12 register-error">Username already exists. Please try another one.</div>';
} else {
$from = get_option( 'admin_email' );
$headers = 'From: ' . $from . "\r\n";
$subject = "Registration successful";
$message = "Registration successful.\nYour login details\nUsername: $username\nPassword: $random_password";
// Email password and other details to the user
wp_mail( $email, $subject, $message, $headers );
echo "Please check your email for login details.";
$error = 2; // We will check for this variable before showing the sign up form.
}
}
}
if ( $error != 2 ) {
?>
<?php if(get_option('users_can_register')) { ?>
<div class="col-md-5 manual-register-form">
<form id="sign-up" action="index.php" method="post">
<p>
<label for="user_login">Username</label>
<input type="text" name="username" class="register-input mb-4" value="<?php if( ! empty($username) ) echo $username; ?>" />
<br />
</p>
<p>
<label for="user_email">Email</label>
<br>
<input type="text" name="email" class="register-input mb-4" value="<?php if( ! empty($email) ) echo $email; ?>" />
<br>
</p>
<input type="submit" id="register-submit-btn" class="mb-4" name="submit" value="Sign Up" />
</form>
<p>Already have an account? Login</p>
</div>
<?php
} else {
echo "Registration is currently disabled. Please try again later.";
}
}
?>
<?php
}
} else {
?>
<p>You are logged in. Click here to go home</p>
<?php } ?>
JQuery
var frm = jQuery('#sign-up');
frm.submit(function (ev) {
jQuery.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
functions.php
function hideout_scripts() {
wp_enqueue_script( 'sign-up', get_template_directory_uri() . '/js/login-signup-jquery.js', array('jquery'), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'hideout_scripts' );
The Event.preventDefault() could work if you would first check your fields on the frontend and / or use AJAX to send the fields to the backend. Now there are multiple options to consider.
Required input fields
HTML5 <input> elements already have some built in validation. With the right attributes they can stop a user from submitting a form if they have they don't meet the requirements for submitting.
Adding a required attribute will let the browser know that this field has to be filled in mandatorily. In combination with a pattern attribute you could add complexity to the requirement, like omitting specific symbols or requiring only alphanumeric characters.
The type attribute can also help here. For example, you have an email field. With the type="email" attribute you can tell the browser that this needs to be a valid email.
<form id="sign-up" action="index.php" method="post">
<label for="user-name">Username</label>
<input id="user-name" type="text" name="username" required/>
<label for="user-email">Email</label>
<input id="user-email" type="email" name="email" required/>
<input type="submit" name="submit" value="Sign Up" />
</form>
Though, inputs can be manipulated by the user by inspecting the element. So don't rely solely on the validity of these attributes.
Check all available input types here.
JavaScript Validation
Like validating in PHP you can also validate in JavaScript, or a combination of both, but we'll get to that later on.
Some of the logic, like checking the username and email fields can be transported over to JavaScript. This is similar to the method above with the attributes but is safer to use because you are in full control, nobody can mess with this behavior.
You will have to check each individual field if they are valid and manually add a message if they don't.
var $form = $('#sign-up');
var regex = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/g;
var error = {
emptyUserName: 'User name should not be empty.',
invalidEmail: 'Please enter a valid email.',
}
// Listen for the submit event.
$form.on('submit', function(event) {
// Create a flag to check form validity with.
var isValidForm = true;
// Select the input fields.
var $userName = $('#user-name');
var $userEmail = $('#user-email');
// Check the user name for empty string.
if ($userName.val() === '') {
console.log(error.emptyUserName);
isValidForm = false;
}
// Check the email for a valid email with the regex.
if (!regex.test($userEmail.val())) {
console.log(error.invalidEmail);
isValidForm = false;
}
// If the form is not completely valid, stop.
// Otherwise, do nothing and let the form submit.
if (!isValidForm) {
event.preventDefault();
return;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="sign-up" action="index.php" method="post">
<label for="user-name">Username</label>
<input id="user-name" type="text" name="username"/>
<label for="user-email">Email</label>
<input id="user-email" type="email" name="email"/>
<input type="submit" name="submit" value="Sign Up" />
</form>
The only problem here is checking doing backend checks, like the if the user already exists. You were on the right path by using AJAX to do that, but it needs to be improved.
AJAX Request
So first thing is that you'll need a way to communicate with the backend. You can do that by sending to the admin-ajax.php file. From there you can specify what you want to do with the received data.
First modify your functions.php so that it will output the URL for the AJAX request. We can do that by outputting it as JSON inside an inline script tag so that the URL is available in JavaScript.
// This will create a JSON string with the AJAX url in it.
$wp_data = json_encode( array(
'ajax' => admin_url( 'admin-ajax.php' ),
) );
function hideout_scripts() {
wp_register_script( 'sign-up', get_template_directory_uri() . '/js/login-signup-jquery.js', array( 'jquery' ), '1.0.0', true );
// That JSON string will be put in an inline script tag before the main script.
// This means that we can use the URL in our main script for an AJAX request.
// The ugly __wp__ name is to ensure that this property will not be overwritten, ever by another script, and therefor breaking our code.
wp_add_inline_script( 'sign-up', "window.__wp__ = {$wp_data}", 'before' );
wp_enqueue_script( 'sign-up' );
}
add_action( 'wp_enqueue_scripts', 'hideout_scripts' );
Now the admin-url.php URL is available in our form validation script. We'll stay in the functions.php and add a hook to which we will be able to communicate to when we want to send a request. Something like an endpoint.
function sign_up_ajax() {
$user_name = isset( $_POST[ 'username' ] ) ? $_POST[ 'username' ] : '';
$user_email = isset( $_POS[ 'email' ] ) ? $_POST[ 'email' ] : '';
// Write your validation and checks here.
echo 'Everything is okay';
die();
}
add_action( 'wp_ajax_nopriv_sign_up_ajax', 'sign_up_ajax') ;
add_action( 'wp_ajax_sign_up_ajax', 'sign_up_ajax') ;
So what I did here is use the wp_ajax_nopriv and wp_ajax hooks to register a sign_up_ajax action endpoint. Whenever we call a HTTP request to the admin-url.php endpoint with an action=sign_up_ajax value it will know that we want to call the sign_up_ajax function.
Now for JavaScript. You already had a large part of the AJAX request. All you have to do it set the URL to the admin-ajax.php file, which is stored in window.__wp__.ajax and add a ?action=sign_up_ajax string after it so the endpoint knows what function to call.
var $form = $('#sign-up');
var regex = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/g;
var error = {
emptyUserName: 'User name should not be empty.',
invalidEmail: 'Please enter a valid email.',
}
// Listen for the submit event.
$form.on('submit', function(event) {
// Prevent the submit right away.
event.preventDefault();
// Create a flag to check form validity with.
var isValidForm = true;
// Select the input fields.
var $userName = $('#user-name');
var $userEmail = $('#user-email');
// Check the user name for empty string.
if ($userName.val() === '') {
console.log(error.emptyUserName);
isValidForm = false;
}
// Check the email for a valid email with the regex.
if (!regex.test($userEmail.val())) {
console.log(error.invalidEmail);
isValidForm = false;
}
// If the form is not completely valid, stop.
// Otherwise, do nothing and let the form submit.
if (!isValidForm) {
return;
}
// From here we send a AJAX request. The ajax URL is available
// on the window object in the __wp__ property.
$.ajax({
url: window.__wp__.ajax + '?action=sign_up_ajax',
method: 'POST',
data: $form.serialize(),
success: function(data) {
console.log(data);
// Check your data, and finally submit the form if the data is good. :)
// if (data === 'Everything is okay') {
// $form.submit();
// }
}
})
});
That's the gist of it. Handling forms is no easy feat in WordPress, but I hope that these examples will help you get further.

Submit and fetch data without refreshing the page

I'm new to php and mySQL. I've created a webpage, it's essentially a noticeboard. The page has a form to submit content and the content is shown below instantaneously. The content appears when the submit button is pressed, but now if I wanted to submit content immediately after the form still displays the echo that says submission was successful. Could someone point me in right direction to get the page functioning in a way that users can submit content one after the other without refreshing the page? Any help is greatly appreciated. Apologies for the messy code.
This is my input code:
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc() ) {
$name = addslashes ($_POST['name']);
$proposal = addslashes ($_POST['proposal']);
}else {
$name = $_POST['name'];
$proposal = $_POST['proposal'];
}
$email = $_POST['email'];
$sql = "INSERT INTO db3". "(name, proposal, email, join_date )
VALUES('$name','$proposal','$email', NOW())";
mysql_select_db('_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
echo "<div class='msg-box' id='msg-box'>Entered data successfully</div>\n";
mysql_close($conn);
This is my form:
<form name="submission" method = "post" action = "<?php $_PHP_SELF ?>" >
<fieldset>
<input name = "name" type = "text"
id = "name" placeholder="Name..." required autocomplete="off">
<input name = "email" type = "text"
id = "email" placeholder="example#gmail.com..." autocomplete="off">
<textarea name = "proposal" type = "textarea" maxlength="1000"
id = "proposal" placeholder="Your proposal goes here..." required autocomplete="off"></textarea>
</fieldset>
<fieldset>
<input name = "add" type = "submit" id = "add" value = "Submit">
</fieldset>
</form>
This is my retrieval code:
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT id, name, proposal FROM db3 ORDER BY ID DESC ';
mysql_select_db('_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo
"<article>".
" <div class='id'> ID :{$row['id']} </div> ".
" <section> <p> {$row['proposal']} </p></section> ".
" <section class='name'><h3> {$row['name']} </h3></section> ".
"</article>"
;
}
mysql_close($conn);
?>
Use this code:
<script>
submitHandler: function(form) {
$.ajax({
url: '',
type: 'POST',
data: $("#submission").serialize(),
success: function() {
alert('submitted data: '$("#submission").serialize());
return false;
}
});
}
</script>
Please change the form line with this one:
<form name="submission" id="submission" method = "post" action = "<?php $_PHP_SELF ?>" >
You can do this using AJAX
You will use javascript to send the data to a PHP script which will process it. The same script will return the new data that was just submitted so you can display it on the page.
An example would be
HTML
<form id="comment">
<input type="text" id="userInput" name="comment" placeholder="Tell us what you feel about this" />
<input type="submit" value="Submit" />
</form>
jQuery
<script>
$("#comment").on('submit', function(e) {
// Stop the form from being submitted the standard way
e.preventDefault();
// Put the user's input into a variable
var userInput = $('#userInput').val();
// Do some validation of the data if needed
// ...
// ...
// Perform AJAX request (a.k.a send the data to the server)
$.ajax({
// There are many parameters one can use here
// Browse the documentation to get familiar with the most useful ones
url: 'proccess.php', // The PHP script that will handle the request
type: 'POST', // This can be set to GET, but in this case we'd use POST
data: { comment: userInput }, // "comment" will result in $_POST['comment'], and userInput is the value of it
// If the script returns a 200 status (meaning the request was successful)
success: function(data) {
// The data variable will be the response from the PHP script
// Depending on what you are going to do with the data returned,
// you may want to ensure it is returned as valid JSON
},
error: function() {
// The request failed - So something here
// ...
// ...
}
});
});
</script>
PHP (process.php)
<?php
$data = $_POST['comment'];
// Do all you would normally do when submitting a post
// ...
// ...
// Now, upon successfully storing the data in your database,
// you can return something to the 'data' variable in the AJAX.success function
?>
Do some research on AJAX and jQuery. It's really fun to work with

How to get AJAX to show a success function and allow the page to update database results

I have the following code that I cannot figure out how to allow my AJAX call to send to my PHP file and then allow my page to show the changes on the page without submitting the form. The reason I need the page to not reload is to allow the success message to display.
What I am trying to do is approve a user and once they have been approved their name will show up in a different section of the page and then I want the success message to display after the changes have been made.
As of now everything works in my database and the status changes. Also the success message shows up where it is supposed to, but the user's name does not move until I reload the page.
How can I get all of this to work without reloading the page?
if( $numrows ) {
while($row = mysqli_fetch_assoc($run)){
if($row['status'] == "Pending"){
$pending_id = $row['id'];
$pending_user_id = $row['user_id'];
$pending_firstname = $row['firstname'];
$pending_lastname = $row['lastname'];
$pending_username = $row['username'];
$pending_email = $row['email'];
?>
<form action="" method="POST" id="status">
<input type='hidden' name='id' value='<?php echo $pending_id; ?>' id='pending_id'/>
<?php
if ($pending_firstname == true) {
echo "Name - ". $pending_firstname . " " . $pending_lastname . "</br>" .
"Username - ". $pending_username . "</br></br>"
?>
<button class="approve" type="submit" form="status" name="approve" value="<?=$pending_id;?>">Approve</button>
<button class="deny" type="submit" form="status" name="deny" value="<?=$pending_id;?>">Deny</button>
</form>
AJAX
$('.approve').click(function () {
$.ajax({
url: 'userRequest_approve.php',
type: 'POST',
data: {
id: $(this).val(), //id
status: 'Approved' //status
},
success: function (data) {
//do something with the data that got returned
$("#success").fadeIn();
$("#success").show();
$('#success').html('User Status Changed!');
$('#success').delay(5000).fadeOut(400);
},
//type: 'POST'
});
return false;
});
UPDATE TO SHOW OUTPUTTED DATA
<h2>Approved User Requests</h2><br>
<div id="success" style="color: red;"></div><br>
$run2 = mysqli_query($con2,"SELECT * FROM user_requests ORDER BY id DESC");
$runUsers2 = mysqli_query($con2,"SELECT * FROM users ORDER BY id DESC");
$numrows2 = mysqli_num_rows($run2);
if( $numrows2 ) {
while($row2 = mysqli_fetch_assoc($run2)){
if($row2['status'] == "Approved"){
//var_dump ($row2);
$approved_id = $row2['user_id'];
$approved_firstname = $row2['firstname'];
$approved_lastname = $row2['lastname'];
$approved_username = $row2['username'];
$approved_email = $row2['email'];
if ($approved_firstname == true) {
echo "Name - ". $approved_firstname . " " . $approved_lastname . "</br>" .
"Username - ". $approved_username . "</br></br>"
Is it the same page you call from your ajax query and for the message success ?
You should use json in your php file, then you can check for any values you add in the callback like this:
userRequest_approve.php
<?php
header('Content-type: application/json');
echo '[{"success":1,"username","theusername"}]';
?>
script.js
$('.approve').click(function(){
$.post('userRequest_approve.php',$('#status').serialize(),function(data){
alert(data[0].success+' username='+data[0].username);
},'json');
return false;
});

PHP remembers POST value after refresh

I've got a problem with a html form. Php seems to remember my POST value after refreshing my page. It has to do with a login form that I uses.
I'm using cookies to let php communicate with javascript, telling javascript if the user is logged in or not.
Php code:
<?php
if (isset($_POST['username'], $_POST['password'])){
$username = $_POST['username'];
$password = MD5($_POST['password']);
echo '<script>console.log("' . $username . '", "username"); </script>';
echo '<script>console.log("' . $password . '" , "password"); </script>';
/* against sql injections */
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$query = "SELECT user_id FROM User WHERE username='$username' AND password='$password'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
if ($row[user_id]){
$cookie_name = "login";
$cookie_value = "1";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
} else{
echo '<script> alert("Incorrect username and password combination");</script>';
}
}
?>
The form:
<form method="POST" id="loginForm">
<b>Login</b>
<table style="margin-top: 10px">
<tr><td>Username: </td><td><input type="text" name="username" placeholder="username" required="required"></td></tr>
<tr><td>Password: </td><td><input type="text" name="password" placeholder="password" required="required"></td></tr>
<tr><td><input type="submit" name="login" value="Login" style="margin-top: 5px"></td></tr>
</table>
</form>
Because I love javascript, I'm using a ajax call to communicate with php and the server database.
Javascript code:
function openPage(page) {
var content;
$.ajax({
type: 'post',
url: '/php/' + page + '.php',
success: function (data) {
document.getElementById('contentMiddle').innerHTML = data;
}
});
}
}
The problem is whenever I try to refresh the page, my php code will always run and $_POST['username'] and $_POST['password'] will always have the POST value from before refreshing the page.
I always make sure I remove the cookie before refreshing the page.
Any idea?
You've most likely already submitted the page and by hitting refresh the browser is attempting to send the POST data along with the refresh.
Since you're using Ajax to process your form you can/should remove type="submit" from the login button since there's no need for it. Instead you can have Login.
Then update your Ajax to run when the button is clicked. You can also use jQuery to get your elements by ID, for example:
$("#btn_login").on("click", function() {
$.ajax({
type: 'post',
url: '/php/' + page + '.php',
success: function (data) {
//document.getElementById('contentMiddle').innerHTML = data;
$("#contentMiddle").html(data);
}
});
});
To address the comment by #charlietfl, handling an Enter press to submit the form you'd use something like this.
document.onkeydown = function(){
if(window.event.keyCode=='13'){
$("#loginForm").submit();
}
}

Validate form with PHP + does not refresh if error is present

I'm trying to validate my form with php upon pressing submit and I want the following :
User press submit, if no errors are found, the registration form is processed and data is sent to database.
If errors are present, the page doesn't refresh and the error console appears.
Every time the user clicks submit, if errors are found the old messages are deleted & new messages posted in the error console div.
I wrote all the code for the form , validation(php) , Error console div & CSS . I just have no idea how to integrate them together
something like:
if ( ($username && $email) != 0 ) { error console + remain on same page } else {send to db};
(source: 1.ii.gl)
PHP VALIDATION CODE
$username = 0;
$uservar = $_POST['username'];
if (empty($uservar))
{
$username = 1;
}
else if (!preg_match("/^\w{5,20}$/",$uservar))
{
$username = 2;
}
if ( ($username) != 0 ) {
echo "<h4 class='error2'><img src='http://s28.postimg.org/ql0x06555/warning6.png' alt='Error'> Error Console</h4> </br>";
switch ($username) {
case 1:
echo "<img src='http://s27.postimg.org/vjxntq073/sign5.png' alt='Error'>";
echo " The Field 'Username' cannot be left blank";
break;
case 2:
echo "<img src='http://s27.postimg.org/vjxntq073/sign5.png' alt='Error'>";
echo " Invalid 'Username' Format - Please use Letters & Numbers only (5-20 Characters)";
break;
}}
</div>
FORM:
<form id="registration-form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="username" id="username" placeholder="Username">
<button type="submit" name="submit" id="submit" class="button-submit">Submit</button>
</form>
split your main php from your html
php in your html only handle simple logical and display result
As a quick answer, please check code below:
<?php
function valiation(){
$aryMsg = array();
$aryExport = array();
if( !isset( $_POST['_submit'] ) ){
//no submit
return array( $aryMsg, $aryExport );
}
$aryPostFieldWhiteList = array( 'username' );
//1. post content filter
//make sure pass all the field you need from $_POST to $aryExport
foreach( $aryPostFieldWhiteList as $strField ){
$aryExport[$strField] = htmlentities( $_POST[$strField], ENT_QUOTES );
}
//2. post content filter
//...
//if username is wrong fill $aryMsg['username'] ... etc
//3. check validation result
if( sizeof($aryMsg) ){
//means not pass the validation, return error message and filtered data
return array( $aryMsg, $aryExport );
}
//4. past validation
//4.1 all db, to insert result
//db insert ...etc
//4.2 page redirect to thank you page
header( 'Location: /thankyou.php' );
die();
}
list( $aryMsg, $aryPost ) = valiation();
?>
<html>
<head>
...
</head>
<body>
<?php if( is_array( $aryMsg ) && sizeof( $aryMsg ) ):?>
<h4 class='error2'><img src='http://s28.postimg.org/ql0x06555/warning6.png' alt='Error'> Error Console</h4>
<ul class="error_msg">
<?php foreach( $aryMsg as $strMsg ):?>
<li><?php echo $strMsg;?></li>
<?php endforeach;?>
</ul>
<?php endif;?>
<form id="registration-form" action="" method="post">
<input type="text" name="username" id="username" placeholder="Username" value="<?php echo $aryPost['username'];?>">
<button type="submit" name="_submit" id="submit" class="button-submit">Submit</button>
</form>
</body>
</html>

Categories