JQuery $.post & php 'if' statement stops working - php

This is pretty specific and I have not found an answer yet.
I am writing a script to check if a name is already input into the SQL server using JQuery $.POST.
The front end looks like this:
register.php
<div id="container" class="container">
<div id="wrapper" class="wrapper">
<div id="title" class="title">
Welcome to Taskar!
</div>
<div id="login" class="login">
<form method="post" action="registermembers.php">
<div id="exists">
Register Your Company Below:
</div>
<input type="text" id="company" name="company" value="Company Name"/> <br />
<br />
<input type="text" id="password" name="password" value="Default Password"/> <br />
<input type="submit" name="submitcompany" value="Submit" />
</form>
<script>
$(document).ready(function() {
$('#company').keyup(function() {
var $company = $(this).val();
var $reg = $('#exists').html();
$.post('include/reg_post.php', { company: $company, reg: $reg }, function(company) {
$('#exists').html(company);
});
});
});
</script>
</div>
</div>
</div>
The backend code looks like this:
reg_post.php
<?php
include 'include/db.php';
$reg = $_POST['reg'];
$company = $_POST['company'];
$email_hash = $_COOKIE['email_hash'];
$password = $_COOKIE['password'];
$sql = "SELECT * FROM taskar_employee WHERE (company = '$company')";
$result = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($result) <= 1){
echo $reg;
} else {
echo "This Company Already Exists!";
} ?>
Now, the problem I am having is, when I am testing this, it works fine all the way up to when I type in a company name that is in the database. It shows me that the company is already registered. When I press backspace or type another letter, it still tells me the company still exists, though it obviously would not.
It seems that the if statement wants to stop the $.post feature from continuing after it gets the opposite statement?
What do you guys think?

Your problem lies in the way you're using your $reg variable.
$reg contains the HTML contents of the #exists div, so it's "Register your Company Below:" to begin with. But, once you've hit a company name that does exist, you replace that HTML with "This Company Already Exists!". From that point on, $reg, on both the JavaScript and PHP sides, is always "This Company Already Exists!" (since you always pass $reg in your POST).
It would probably be much easier if the contents of that div weren't passed to or handled by the PHP code at all. It'd be simpler if your PHP script just returned "1" if the company existed, and "0" if not (or some other equally simple flags).
Then, on the JavaScript side, you could just do:
$.post('include/reg_post.php', { company: $company }, function(exists) {
var message;
if (exists === '1') {
message = 'This Company Already Exists!';
}
else {
message = 'Register Your Company Below:';
}
$('#exists').html(message);
});

You're passing $('#exists').html(); to be returned in the event that the company is not found. The problem is, in the event that the company is found, you replace the html within #exists. Then the next time you call the post you pass this text back along so in this case:
if(mysql_num_rows($result) <= 1){
echo $reg;
} else {
echo "This Company Already Exists!";
}
your $reg is now set to This Company Already Exists! so regardless of what happens you're going to return that text.

Related

How to pass and put variable from a php page into a another page(form)?

I working on two pages, a first one which has a form with three fields: name, email and message). This page will send these data to a second page, that will validate if those fields meet the criteria.
If on the second page, any of those fields does not meet the criteria, I want to redirect to the first page (or a third php one), fill the form with previous information and tell the user to correct the fields properly.
I'm strugling to send the data form the second page to the first (or third) one. Does anyone knows a good way to do it?
Here's my code:
First page - contato.html
<form action="validate.php" method="POST" name="emailform">
<div class="form-group">
<input type="text" id="name" name="nome" placeholder="Type your name">
</div>
<div class="form-group">
<input type="text" id="email" name="email" placeholder="type your#email.com here">
</div>
<div class="form-group">
<textarea class="form-control" cols="30" rows="10" maxlength="300" id="message" name="mensagem" placeholder="Leave your message." ></textarea>
</div>
<div class="form-group">
<input type="submit" name="submit" value="Send message" onclick="alert('Thank you!')" ></form>
Second Page - validate.php
if(isset($_POST['nome'])) $nome = $_POST['nome'];
if(isset($_POST['email'])) $email_visitante = $_POST['email'];
if(isset($_POST['mensagem'])) $mensagem = $_POST['mensagem'];
// if does not meet the criteria, redirect to contato.html and update the form with the info
if(empty($nome)){
Header("location:contato.html");
}
if(empty($email_visitante)){
Header("location:contato.html");
}
if(empty($mensagem)){
Header("location:contato.html");
}
// check for letters and space only
if (!preg_match("/^[a-zA-Z ]*$/",$nome)) {
Header("location:contato.html");
}
// check if e-mail address is well-formed
if (!filter_var($email_visitante, FILTER_VALIDATE_EMAIL)) {
Header("location:contato.php");
}
Does anyone knows how to do it? Either sending to a third page or redirecting to the first one (and fill the form in again)
You have to use sessions and store data there in one page and access in another, here is a small usage
<?php
// page 1
session_start();
// Set session variables
$_SESSION["nome"] = $nome;
$_SESSION["email"] = $email_visitante;
$_SESSION["mensagem"] = $mensagem;
<?php
// page 2|3|N - any other page
session_start();
// Get session variables
$nome = $_SESSION["nome"];
$email_visitante = $_SESSION["email"];
$mensagem = $_SESSION["mensagem"];
Part of your problem is that upon any failed validation you are using a redirect. Alternatively you can display an error message to the user: suggesting they need to correct their input by going back a page (browser back).
When forms get longer users need some hand holding with error correction. Their errors need to be clearly indicated with a message alongside as to how they can fix it.
Avoiding using the 'browser back' method above it's common to have the form send to its own url. I've included an example below.
By doing this you can repopulate the form with posted values upon error and add error feedback. You must be careful to escape user input in this situation.
I've added a generic error feedback notice. Which isn't that helpful in its current form. You could improve upon this by adjusting the validation code to return an array of error notices and use that within your form for more targeted error feedback. You could also add - all fields are required - text to help the user.
Upon successful validation that's when to redirect the user to a confirmation page. This can prevent form resubmissions.
Your name regex pattern in its current form will not allow hyphens or apostrophes. I haven't changed it below. Do bear this in mind. "Michael O'leary" would be faced with an error and likely not understand why. You need to be careful when using strict rules for user input. Also this will reject some unicode.
You also need to escape user input appropriately. Note that you may be satisfied that the name and email after validation follows a particular pattern, but becareful of raw user input. The message text is passed on raw after validation.
<?php
$nome = $_POST['nome'] ?? null;
$email_visitante = $_POST['email'] ?? null;
$mensagem = $_POST['mensagem'] ?? null;
$feedback = null;
if(isset($_POST['submit'])) {
if(validate($nome, $email_visitante, $mensagem) !== false) {
process($nome, $email_visitante, $mensagem);
// Redirect to success/thankyou/confirmation page.
header('location:success.html');
exit;
}
// This is a generic message, could this be more helpful?
$feedback = 'Your form has errors. Please correct them.';
}
form($nome, $email_visitante, $mensagem, $feedback);
function process($nome, $email_visitante, $mensagem) {
// do something with your values.
}
function validate($nome, $email_visitante, $mensagem) {
if(empty($nome)) {
return false;
}
if(empty($email_visitante)){
return false;
}
if(empty($mensagem)){
return false;
}
if (!preg_match("/^[a-zA-Z ]*$/",$nome)) {
return false;
}
if (!filter_var($email_visitante, FILTER_VALIDATE_EMAIL)) {
return false;
}
return true;
}
function form($nome = null, $email_visitante = null, $mensagem = null, $feedback = null) {
?>
<?= $feedback ?>
<form action='' method='POST' name='emailform'>
<div class='form-group'>
<label for='name'>Your name:</label>
<input type='text' id='name' name='nome' value='<?= htmlspecialchars($nome) ?>'>
</div>
<div class='form-group'>
<label for='email'>Your email address:</label>
<input type='text' id='email' name='email' value='<?= htmlspecialchars($email_visitante) ?>'>
</div>
<div class='form-group'>
<label for='message'>Your message:</label>
<textarea class='form-control' cols='30' rows='10' maxlength='300' id='message' name='mensagem'><?= htmlspecialchars($mensagem) ?></textarea>
</div>
<div class='form-group'>
<input type='submit' name='submit' value='Send message'>
</div>
</form>
<?php
}

form validation with red error messages not working (php, ajax, jquery, and mysql)

Well, brothers, I'm having a problem with the appearance of notices concerning the form validation. I associate the problem to a few issues on the php code like arrays defined by the variables $errors and $data. I really didn't understand the usage of them. Or maybe it's related to somewhere in the jQuery code.
These codes were based on a website tutorial I've found on the internet. Also, I have no experience in the Ajax and jQuery arenas. Maybe you can solve this simple issue. I even appended the screen captures of the sign up page along with the next page which processes the php connection with database.
This is the sign up page called join_form.php
This is the processing page called register2.php
This is html code:
<html>
<head>
<title>
This is the form page
</title>
</head>
<body>
<center>
<br>
<br>
<img src="images/quintz.png" width="156" height="44" alt=""/>
<br>
<br>
Register now
<br>
<br>
<div id="bugado">
<form id="ajax_form" method="post" action="register2.php">
<div id="usertype-group" class="form-group">
<label for="usertype">
You're a
</label>
<select name="usertype" class="form-control">
<option value="native speaker">
Native speaker
</option>
<option value="non-native speaker">
Non-native speaker
</option>
</select>
<br>
<!-- errors will go here -->
</div>
<div id="username-group" class="form-group">
<label for="username">
Create username:
</label>
<input name="username" type="text" maxlength="30" class="form-control" placeholder="Username">
<br>
</div>
<div id="email-group" class="form-group">
<label for="email">
Email:
</label>
<input name="email" type="text" maxlength="50" class="form-control" placeholder="Email">
<br>
<!-- errors will go here -->
</div>
<div id="password-group" class="form-group">
<label for="password">
Create password:
</label>
<input type="password" name="password" class="form-control" placeholder="Password">
<br>
</div>
<label>
Confirm password:
</label>
<input type="password" name="confirm_password" class="form-control" placeholder="Password again">
<br>
<button type="submit" name="submit" class="btn btn-success">
Submit
</button>
<span class="fa fa-arrow-right">
</span>
<br>
<input name="reset" type="reset" value="Reset">
</form>
</div>
</center>
</body>
</html>
This is the jQuery code:
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.js"></script>
<script language="javascript">
$(document).ready(function() {
// process the form
$('#ajax_form').submit(function(event) {
$('.form-group').removeClass('has-error'); // remove the error class
$('.help-block').remove(); // remove the error text
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'usertype' : $('select[name="usertype"]').val(),
'username' : $('input[name="username"]').val(),
'email' : $('input[name="email"]').val(),
'password' : $('input[name="password"]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : $(form).attr('action'), // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
if ( ! data.success) {
// handle errors for usertype ---------------
if (data.errors.usertype) {
$('#usertype-group').addClass('has-error'); // add the error class to show red select
$('#usertype-group').append('<div class="help-block">' + data.errors.usertype + '</div>'); // add the actual error message under our select
}
// handle errors for username ---------------
if (data.errors.username) {
$('#username-group').addClass('has-error'); // add the error class to show red input
$('#username-group').append('<div class="help-block">' + data.errors.username + '</div>'); // add the actual error message under our input
}
// handle errors for email ---------------
if (data.errors.email) {
$('#email-group').addClass('has-error'); // add the error class to show red input
$('#email-group').append('<div class="help-block">' + data.errors.email + '</div>'); // add the actual error message under our input
}
// handle errors for superhero alias ---------------
if (data.errors.password) {
$('#password-group').addClass('has-error'); // add the error class to show red input
$('#password-group').append('<div class="help-block">' + data.errors.password + '</div>'); // add the actual error message under our input
}
} else {
// ALL GOOD! just show the success message!
$('#ajax_form').append('<div class="alert alert-success">' + data.message + '</div>');
// usually after form submission, you'll want to redirect
// window.location = '/thank-you'; // redirect a user to another page
alert('success'); // for now we'll just alert the user
}
})
// using the fail promise callback
.fail(function(data) {
// show any errors
// best to remove for production
console.log(data);
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
</script>
And this is the php code:
<?php
include 'db.php';
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
//Searching for identical usernames
$search = mysql_query("SELECT * FROM natspeaker WHERE username = '".$_POST['username']."'");
$count = mysql_num_rows($search);
$search2 = mysql_query("SELECT * FROM nonnatspeaker WHERE username = '".$_POST['username']."'");
$count2 = mysql_num_rows($search2);
//Searching for identical emails
$search3 = mysql_query("SELECT * FROM natspeaker WHERE email = '".$_POST['email']."'");
$count3 = mysql_num_rows($search3);
$search4 = mysql_query("SELECT * FROM nonnatspeaker WHERE email = '".$_POST['email']."'");
$count4 = mysql_num_rows($search4);
//if( isset( $_SERVER['REQUEST_METHOD'] ) && $_SERVER['REQUEST_METHOD']=='POST' ) {
if(isset($_POST)){
//USERTYPE
if(empty($_POST['usertype'])) {
$errors['usertype'] = "Please select if you are a native or a non-native speaker.<br>";
}
//USERNAME
if (empty($_POST['username'])) {
$errors['username'] = "Username is missing<br>";
}else{//this "else" can be deleted
/*this can be deleted in case of trouble*/if ( $count == 1 OR $count2 == 1) {
$errors['username'] .= "Username already exists in our database. Choose another one<br>";
}
}//this bracket can be deleted.
//EMAIL
if (empty($_POST['email'])) {
$errors['email'] = "Email is missing<br>";
}else{//this "else" can be deleted
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $_POST['email'])) {
$errors['email'] = "Invalid email<br>";
}
if ( $count3 == 1 OR $count4 == 1) {
$errors['email'] = "Email already exists in our database. It seems you have an account yet.<br>";
}
}//this bracket can be deleted.
//PASSWORD
if (empty($_POST['password'])) {
$errors['password'] = "Password is missing.<br>";
}else{//this "else" can be deleted
if (strlen($_POST['password']) < 6) {
$errors['password'] = "Password too short<br>";
}
}//this bracket can be deleted.
// return a response ===========================================================
// if there are any errors in our errors array, return a success boolean of false
if ( ! empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
//if(count($_SESSION['errors']) > 0){
//This is for ajax requests:
if( isset( $_SERVER['REQUEST_METHOD'] ) && $_SERVER['REQUEST_METHOD']=='POST' ) {
//if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH'])== 'xmlhttprequest') {//something is wrong with this
header('Content-type: application/json');
echo "Ajax request is working.";
echo json_encode($data);//now this iss working
exit;
}
//This is when Javascript is turned off:
echo "<br><br><br><center><div style=\"font-size:50;\">something is wrong or your Javascript is turned off. Ajax request is not working</div></center><br><br>";//delete
echo $data;//delete
//foreach($_SESSION['errors'] as $key => $value){
//echo "<li>" . $value . "</li>";
//}
//echo "</ul>";exit;
}else{
// if there are no errors process our form, then return a message
// DO ALL YOUR FORM PROCESSING HERE
// THIS CAN BE WHATEVER YOU WANT TO DO (LOGIN, SAVE, UPDATE, WHATEVER)
if ( $_POST['usertype'] == "native speaker") {
$register = mysql_query("INSERT INTO natspeaker(username, email, password, time1, usertype)
VALUES ('".$_POST['username']."','".$_POST['email']."', '".$_POST['password']."', now(), '".$_POST['usertype']."')") or die (mysql_error());
}elseif ( $_POST['usertype'] == "non-native speaker"){
$register = mysql_query("INSERT INTO nonnatspeaker(username, email, password, time1, usertype)
VALUES ('".$_POST['username']."', '".$_POST['email']."', '".$_POST['password']."', now(), '".$_POST['usertype']."')") or die (mysql_error());
}
// Let's mail the user!
$subject = "Your Membership at Quintz!";
$message = "Hi, ".$_POST['username'].",
Thank you for registering at our website, http://www.quintz.club!
You have registered as a ".$_POST['usertype'].".
You are two steps away from logging in and accessing our exclusive members area.
To activate your membership, please click here: http://www.quintz.club/activate.php
Once you activate your membership, you will be able to login.
And please do not forget to complete your profile.
Thanks!
The Webmaster
This is an automated response, please do not reply!";
mail($_POST['email'], $subject, $message, "From: Quintz Webmaster<support#quintz.club>\nX-Mailer: PHP/" . phpversion());
// show a message of success and provide a true success variable
$data['success'] = true;
$data['message'] = 'Your account has been created successfully. Go to your email address and activate your account.';
echo "successful register!";//delete
}
}
//}
// return all our data to an AJAX call
//this works
//echo json_encode($data);//delete
?>
In sum, I just want to hinder the user from registering with a username that already exists in the database, or with an invalid email, or even missing information (blank fields), and just return those red notices in the same page join_form.php. The user can only go to the register2.php, if all information are approved to be passed to the database and finally exhibits the message "Successful register!" on this page and sends an email to the user. Just that!
I think you need to go back to the beginning. Your HTML is clearly not on par and your PHP code is.. aged..
Go through what your code is doing, start with HTML, then do the form using jQuery where the output is just either true or the ID of the form field that failed, or something like it.
Just a few quick things;
title goes inside head, not above it
mysql_query is outdated, try using mysqli_query or the OOP variant of that
Do counts when necessary, if the entire form is empty there's no reason to bug the mysql server
Using OOP mysqli, you could just do $s = $mysqli->query('SELECT [..]'); and then if($s->num_rows > 0) instead of making a new variable of the count, using that same way to verify a user does exist for logging in and then just using $r = $s->fetch_assoc() to get the user's details.
Instead of grabbing the values, try writing them all to an array using $('#form').serialize() and then mosting that
In short, go back to the beginning, start over from scratch and use an updated tutorial.

How to make multiple AJAX queries after user input?

This seems like such a simple thing, but I have not been able to find adequate guidance on it for the life of me. I have only been able to find things about successive AJAX queries regardless of user input, like this or this.
What I'm trying to do is create a survey such that after a user answers a question, the website replaces the question with the next question, and so on.
Here's what I have so far (in a .php file):
In <head>, I have a function for each successive element to call:
<script type="text/javascript">
function nextPage(url) {
$("#consent-form").empty();
$("#consent-form").load(url);
}
</script>
Maybe that's just not how it's done. I have no idea. Like I said, I have not been able to find adequate help on this. As far as I can tell, empty() should not delete #consent-form, but only its content and children, which is exactly the behavior I want.
This is the initial html and php for the div I want to swap out after each answered question:
<div id="consent-form">
<?php
// Check for a valid email address.
$email = $emailErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["email"])) {
$emailErr = "* Your email address is required.";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "* Please enter a valid email address.";
} else {
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$query = "INSERT INTO survey VALUES ('" . $email . "','" . $actual_link . "','','')";
mysql_query($query);
echo '<script type="text/javascript">'
, 'nextPage("survey.php");'
, '</script>'
;
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<p>
[Consent form text]
</p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Please enter your email address: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error"> <?php echo $emailErr;?></span>
<br>
<input type="submit" value="Begin Study">
</form>
</div>
As I'm sure you can tell, I'm trying to do some form validation there.
This succcessfully injects the content of the next page ("survey.php") into the consent-form div. "survey.php" includes the following, using the nextPage() function shown above:
$("#csp_form").on('submit', function() {
nextPage("other.php");
});
But this fails to inject the consent-form div with "other.php".
Now, however, not even the form validation works. According to Firebug, the jquery library has raised some sort of error, even when I comment out all the jquery and javascript functions, and it's stuck in some perpetual loading operation. (This issue has been fixed.)
I am about to start throwing things. I have tried many different other techniques, but none of them worked and I have lost track of them. Hopefully this latest version will be sufficient to get guidance on this.
Sorry all that was so long, but usually people complain that there's too little information, so I wanted to make sure to include everything.
EDIT:
Per request, here's the current full content of survey.php (with the text content changed for privacy purposes):
<script type="text/javascript">
$("#icecream_form").on('submit', function() {
nextPage("other.php");
return false;
});
</script>
<br>
<h2>What's your favorite ice cream flavor?</h2>
<form method="post" id="icecream_form">
<input type="radio" name="icecream" value="vanilla"> Vanilla
<br>
<input type="radio" name="icecream" value="chocolate"> Chocolate
<br>
<input type="radio" name="icecream" value="other"> Something else
<br>
<input type="radio" name="icecream" value="none" checked> I don't have a favorite.
<br>
<br>
<input type="submit" name="icecream_submit" value="Go" onsubmit="return(false)">
</form>
After hitting submit, the content from consent-form comes back with an error message from the email form ("Please enter an email address"), implying that the email form was posted again. I cannot comprehend how that is possible if all the stuff from that div had truly been replaced by the stuff in survey.php.
I believe the issue was just that I was missing $(document).ready(function () { before $("#icecream_form").on('submit', function() {. This enabled return false; to actually work.
However, I also swapped out the PHP form validation with a jQuery version and deleted the nextPage() function in lieu of just having each page have their own .load(), so those things may also have made a difference.

PHP: Refresh page on invalid form submit

How can I refresh a page with a form on submission pending the outcome of the submitted data and display a result.
e.g I have a page with a form:
<form action="" method="post">
<input type="name" value="" name="name" placeholder="Your Name" />
<input type="button" name="submit" value="submit form "/>
</form>
The engine that handles the form is external, but required in the page:
require_once 'form_engine.php';
form_engine.php checks the input,
$success = "true";
$errorMessage = " ";
$name = $_POST['name'];
if ( $name == '') {
$errorMessage = 'Please enter your name';
$success = false;
}
else (if $success = true) {
// do something with the data
}
The form page contains the result:
<form action="" method="post">
<input type="name" value="" name="name" placeholder="Your Name" />
<input type="button" name="submit" value="submit form "/>
</form>
<p><?php echo $errorMessage; ?></p>
Will the error message get displayed after the form is submitted incorrectly? Or do I have to use a session to store it?
You need something like this:
if (!isset($_POST['name']))
instead of
if ( $name == 'name')
UPDATE
Try this, it should give you the idea:
<?php
$errorMessage = false;
if (isset($_POST['submit'])) {
if (!isset($_POST['name']) || $_POST['name']=='') {
$errorMessage = 'Please enter your name';
}
else {
// do something with the data
echo "Success!!";
}
}
?>
<form method="post">
<input type="name" value="" name="name" placeholder="Your Name" />
<input type="submit" name="submit" />
</form>
<p><?php if ($errorMessage) echo $errorMessage; ?></p>
Note: leaving out the action attribute will just submit the form to the current page
Note 2: The PHP here could very well be stored in another page. Using require() is the same as putting the code directly into the page.
You can use redirect on php side:
header('Location: www.mysite.com/index.php');
You seem to be a little confused in terms of the exact process that occurs in terms of rendering a page, as do some of those commenting. You do not need to use sessions to solve this problem. There is no need to store anything server-side between page requests because the user's browser with retain everything that you need, at least for this situation. My guess is the others took you mentioning an "external engine" and thought that the form would be submitting away to a different site/page.
form loops
Below is a diagram showing a typical form request loop:
You do not have to do this, as coding is as much about personal preference to anything else, but typically people will design their form to submit back to the same URI that generated it — as you seem to be doing in your example, by leaving the action attribute blank. By doing this, as long as you embed everything you wish to pass back to the server side within the form — each time the user submits — that information will be resent and be available in PHP.
Obviously you need to be wary of what information might constitute as sensitive, as this data should only ever be written into markup if your requests are protected by HTTPS/SSL. You should also filter/escape any user input to prevent markup injection into your site. You can prevent many problems by using htmlentities, however this can cause issues depending on the values you are trying to capture from the user. Because you are using double quoted HTML attributes (the right way to do them ;) I have not set the ENT_QUOTES option.
back to the point
So in the above loop the user will be shown the form for the first time, and after any subsequent submit, which means that each time your PHP notices that there is an error you can just add your message into the page flow. The trick with this kind of system is what exactly do you do once the form is fully complete. To get out of the loop most people will use a header location call:
<?php
require_once 'form_engine.php';
$name = !empty($_POST['name']) ? trim($_POST['name']) : '';
$name = htmlentities($name);
if ( $success ) {
header('location: next-step.php');
exit;
}
?>
<form action="" method="post">
<input type="name" value="<?php echo $name; ?>" name="name" placeholder="Your Name" />
<input type="button" name="submit" value="submit form "/>
</form>
<?php
if ( $errorMessage ) {
echo "<p>$errorMessage</p>";
}
?>
form engine repairs
You should also rectify your form_engine.php as per my comments above and Shekhar Joshi's answer, although I would keep the header code outside of your engine logic, and leave that decision to the code that requires in the engine — as the above does.
may be, you are looking for this! the header() method.
$success = true;
$errorMessage = " ";
$name = $_POST['name'];
if(isset($_POST['name'])) {
if ( $_POST['name'] == '') {
$errorMessage = 'Please enter your name';
$success = false;
header('Location: www.something.com/some.php');
}
else if ($success == true) {
// do something with the data
}
}

PHP: Using POST on a dynamic page redirects me to index.php and does not post the values

I am trying to get a guest book to work using PHP. I have managed to make it function, the thing is that I don't want the guest book to be in my index.php. I want it to be on a dynamic page, index.php?=guestbook for instance.
The problem is that when I put the code on another page rather than index.php the thing that happends when I fill out the fields and press the submit button, I get redirected to index.php and nothing is submited to my database. This all works fine as long as the code is in the index.php.
My first question is: What is causing this?
Second question: How do I get the code to function properly eventhough I have it in index.php?=guestbook?
Thanks in advance!
I am using xampp btw.
See below for the code:
<html>
<head>
<link rel="stylesheet" href="stylesheet.css" type="text/css">
</head>
<body>
<h1>Guestbook</h1><hr>
<?php
mysql_select_db ("guestbookdatabase") or die ("Couldn't find database!");
$queryget = mysql_query ("SELECT * FROM guestbook ORDER BY id ASC") or die("Error witch query.");
$querygetrownum = mysql_num_rows ($queryget);
if ($querygetrownum == 0)
echo "No posts have been made yet. Be the first!";
while ($row = mysql_fetch_assoc ($queryget))
{
$id = $row ['id'];
$name = $row ['name'];
$email = $row ['email'];
$message = $row ['message'];
$date = $row ['date'];
$time = $row ['time'];
if ($id%2)
$guestbookcomment = "guestbookcomment";
else
$guestbookcomment = "guestbookcommentdark";
echo "
<div class='$guestbookcomment'>
<div class='postheader'>
<b>Posted by $name ($email) on $date at $time</b>
</div>
<div class='message'>
".nl2br(strip_tags($message))."
</div>
</div>
";}
echo "<hr>";
if($_POST['submit'])
{
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$date = date("Y-m-d");
$time = date("H:i:s");
if ($name&&$email&&$message)
{
$querypost = mysql_query ("INSERT INTO guestbook VALUES ('','$name','$email','$message','$date','$time')");
echo "Please wait... <meta http-equiv='refresh' content='2'>";
}
else
echo "Please fill out all fields.";
}
echo "
<form action='index.php' method='POST'>
Your name: <input type='text' name='name' class='name' maxlength='25' ><br> <br>
Your email: <input type='text' name='email' class='email' maxlength='35'><br><br>
<div class='your_message'>
Your message:<input type='textarea' name='message' class='messagetextarea' maxlength='250'><br><br>
</div>
<input type='submit' name='submit' value='Post'>
</form>
";
?>
</body>
</html>
1) The action property of your form should be the same as the name of the file where the code is in. :) You create a guestbook.php, for example, but the action still is 'index.php'. Hence the problem. You send the POST data to index.php but there's no code to process it.
2) The query string doesn't affect the form. Only the filename.
I hope I understood your problem correctly.
Have you tried updating your form's action parameter to:
index.php?=guestbook
instead of just index.php?
If the problem resides on the server end than the victim to your problem is .htaccess (mod rewrite);
Otherwise, what do you really mean by this line of code?
echo "Please wait... <meta http-equiv='refresh' content='2'>";
< meta > refresh tag requires location to be mentioned where the redirect otherwise according to you refreshes the current page..
<meta http-equiv="refresh" content="2;url=http://stackoverflow.com/">
First, I'm assuming the file you're showing is index.php
Second, don't use index.php?=guestbook. URL parameters work within a key => value structure. In you're case you've only defined the value and no key.
Try using index.php?page=guestbook. this way, in your index.php file you can do something like:
if($_GET['page'] == 'guestbook') {
// ... your guestbook php code.
}
Then try setting your forms action attribute like this: action="index.php?page=guestbook".
Third, I'm going to assume that you have mysql connection code that isn't shown here. If not, take a look at mysql_connect().
Fourth, NEVER use unescaped data in a SQL query. You MUST escape your data to protect your database from being destroyed. Take a look at this wikipedia article which describes SQL Injection in greater detail: http://en.wikipedia.org/wiki/SQL_injection
Then take a look at mysql_real_escape_string() to learn how to prevent it with PHP and MySQL.
Fifth, don't use <meta http-equiv='refresh' content='2'> for redirect. Use PHP's header() function to redirect users, like this:
header('location: index.php');
exit(); // be sure to call exit() after you call header()
Also, just so you know, you CAN close PHP tags for large HTML blocks rather than using echo to print large static chunks of HTML:
<?php
// ... a bunch of PHP
?>
<form action="index.php" method="POST">
Your name: <input type="text" name="name" class="name" maxlength="25" ><br> <br>
Your email: <input type="text" name="email" class="email" maxlength="35"><br><br>
<div class="your_message">
Your message:<input type="textarea" name="message" class="messagetextarea" maxlength="250"><br><br>
</div>
<input type="submit" name="submit" value="Post">
</form>
<?php
// ... some more PHP
?>

Categories