I'm using this code:
if(isset($_POST['btitle'])) {
if(count($errors) > 0) {
foreach($errors as $error)
$errContent .= "<li>".$error;
echo notification(
$errContent,
FALSE,
"The following errors were encountered:"
) . "<div style='margin-bottom: 10px;'></div>";
}
else {
echo notification(
"<li>New form added!",
TRUE,
"Success:"
) . "<div style='margin-bottom: 10px;'></div>";
}
}
When I type something in the input named 'btitle' and hit the submit button, everything is fine, until I refresh the page - it should loose the data and start again after refreshing, but it keep saying "Success:" even if the 'btitle' input is empty.
What am I doing wrong?
you need to redirect the user to the same page and loose the post data.
header("Location: file.php?success=true");//or ?errors[]=blabla
exit();
now, in the same page (file.php) you need to:
if(isset($_GET['success']) && $_GET['success'] == true){
//handle true
}else if(/* here you can ask about errors or what ever */){
}
BTW, if you don't do it, the entire submitting form will be act again like you resubmit it.
for instance, if you insert data to the database, it will be insert over and over again when you refresh the page, so if you redirect as suggested, you loose the posted data and now you can show the errors or success.
When you hit refresh, your browser resends POST data to the page. This question has been asked many times, for instance here and here. Take a look at the answers to some of those questions to get an idea of what you can do.
Related
I'm trying to make you redirect to the successful page after succesfully registering but whenever I click the register button I get redirected instantly even if all the input's are empty
if(isset($_POST["registration"])){
if(!empty($_POST["gender"])
and !empty($_POST["username"])
and !strlen($_POST["username"]) < 3
and !empty($_POST["email"])
and !email($_POST["email"])
and !empty($_POST["emailver"])
and !verification($_POST["email"],$_POST["emailver"])
and !empty($_POST["password"])
and !strlen($_POST["password"]) < 8
and strlen($_POST["password"]) < 25
and checkUppercase($_POST["password"])
and checkLowercase($_POST["password"])
and checkNumber($_POST["password"])
and !empty($_POST["passwordver"])
and !verification($_POST["password"],$_POST["passwordver"])){
if(addgamer($db,$_SESSION["gender"],$_SESSION["username"],$_SESSION["email"],$_POST["password"]) === TRUE){
$url = 'succesfull.html';
header($url);
}
}
}
The function for addgamers
function addgamer($db,$gender,$username,$email,$password){
$sql = "INSERT INTO gamers (`gender`, `username`, `email`, `password`) VALUES('$gender','$username','$email','$password')";
$db -> exec($sql);
if ($db->query($sql) === TRUE) {
$GamerId = $db -> lastInsertId();
$_SESSION['GamerId'] = $GamerId;
return true;
} else {
return false;
}
}
I found some answers here but all of them do the same and I have no solution for this.
GOTO($url);
Or
header('location: $url');
Or
if(addgamer($db,$_SESSION["gender"],$_SESSION["username"],$_SESSION["email"],$_SESSION["password"]) === FALSE ){
die();
}else{
$url = 'successful.php';
header($url);
}
Also tried with jQuery
echo "<script>window.location = '$url'</script>";
On every single click on the registration submit button you get redirected to the successful page but that should not happen until everything is filled in correctly as shown from the above code.
As you can also see I'd like to fix this problem trying with php only first.
Validate before submitting the form would be better at first.
As #Nicolas D mentioned you should also know that the form action is the page you direct to no matter what.
You can however set this to the current page by using action="" or action="<?php echo $_SERVER['PHP_SELF']; ?>"
This last could come with exploits, you can use "htmlentities($_SERVER['PHP_SELF'])" instead. Read about this here.
You have a missunderstanding PHP problem.
If your form use a submit form, it will post automatically to the php page targeted.
If you don't want to post to a new page and still verify your data, then you must use ajax in jquery : http://api.jquery.com/jquery.post/ . With that you ll catch your data without unexpected redirection.
Once all your form is validated by your php code during ajax call, you can redirect in jquery on the callback function.
Hope this will help, I ve been through this step and I remember it was painful
I have a page which allows the user to "create a topic", open submitting this the form goes to another through a verification process which inserts the topic into the database and re-directs to back to the main page. However I want my verification page "add topic" to display an error message if all fields are not filled in. here is a my code, please can you tell me where I would need to add this validation code to notify the user to fill all fields:
// get data that sent from form
$topic=$_POST['topic'];
$detail=$_POST['detail'];
$name=$_POST['name'];
$email=$_POST['email'];
$datetime=date("d/m/y h:i:s"); //create date time
$sql="INSERT INTO $tbl_name(topic, detail, name, email, datetime)VALUES('$topic', '$detail', '$name', '$email', '$datetime')";
$result=mysql_query($sql);
if($result){
echo "Successful<BR>";
echo "<a href=main_forum.php>View your topic</a>";
}
else {
echo "ERROR";
}
mysql_close();
My suggestion would be create a separate php file called validation and inside the validation file add a function. Of course you can create this function inside the same php file. If you made the separate use an include statement to place it on your page. Also a quick post-back to itself would be good since you could easily be able to get access to the posted variables and already be on the page to show errors. Otherwise you would have to return the Errors in a get, post or session. If everything was successful you could post or redirect right after the postback (maybe to a success page) and the user would only see the postback if errors present.
include_once("Validation.php");
as shown above.
validateNewTopic($topic, $detail, $name, $email, $datetime)
{
}
Then inside you could use if statements to check conditions. If you want a quick solution you can create a variable to hold all the errors.
$Error = "<p class='errors'">;
if ($topic == "")
{
$Error+="topic is required";
}
if ($Error != "<p class='errors'">)
{
return $Error +"</p>";
}
else
{
return "";
}
Since you are posting the values you can catch them in a variable on postback to validate.
$topic = $POST['topic'];
$Error=validateNewTopic($topic);
if ($Error != "")
{
?>
echo $Error
<?php
}
else {
//run sql code and show success
}
By putting the paragraph tags inside the $Error messages we can just echo and it will already be in the paragraph tag with the class errors. You can make it prettier by using an un-ordered list and when adding an error using list items. I'm not sure how familiar you are with php but at anytime you can stop writing php code by closing the tags. (< php ?> and reopen < ? php) as shown above in the if statement. I know this was not 100% clear but this is something you should try/research and practice since it is used so often. Good luck!
You can send the error to the main page by using php GET request, and then display it.
Basically I'v got a HTML Form that links to a php file in a different location for it's action, Currently I'm using the form to update the users profiles and then send them back to the editprofile.php. Basically at the top of editprofile.php if they've submitted the query I want to display the result of either "Profile Updated" or "Failed to Update", issue is I can't workout how to display query results when the query is in a different file.
I tried to do this;
<?php
if(!$query)
{
echo '<div class="editfail">Profile failed to update!</div>';
}
else
{
echo '<div class="editsuccess">Profile successfully updated!</div>';
}
?>
Except the issue with this is that the query hasn't been run on this page, it was run from another page and then redirected back to the editprofile page using a header, so how can I display the same results as above when the query is being executed from another location?
You can send parameter when you are redirecting back the file.
example
if(mysql_query($update_query))
{
header('location:editprofile.php?msg="success to save"');
}
else
{
header('location:editprofile.php?msg="failed to save"');
}
Or even you can send flag also
if(mysql_query($update_query))
{
header('location:editprofile.php?flag=0');
}else
{
header('location:editprofile.php?flag=1');
}
And check the value of flag in your editprofile.php file to display proper message.
You shouldn't mess around with the headers fxn unless you need to - depending on output_buffer settings etc they can be a pain:
You can do what you want - all in 1 single page:
So something like this -As a matter of common convention, and to a degree security, you should post the form to itself - you can integrate whatever else from the other page into the pass/fail profile logic block:
<?php
$query = htmlentities($_POST['profiletext']); #sanitize avec tu code du jour
if(!$query || $query != 'someacceptablevalue))
{
#If it's not posted, or its not a good value, tell them it failed
# and redisplay the form to try again
$query_msg = '<div class="editfail">Profile failed to update!</div>';
$profile_form = "<div_class='profile_rest_of_page stuff'>
<form action='#' method='post'>
<input type='text' id='profiletext' name='profiletext/>
</form>
</div>";
}
else
{
# They did it - Success, and link to next step
$query_msg = '<div class="editsuccess">Profile successfully updated!</div>';
$profile_form = 'No form needed - you did it';
}
#One block below handles all in 1 page with above logic:
echo "<body>
<div class='profile_message_container'>
$query_msg
</div>
<div_class='profile_rest_of_page stuff'>
$profile_redo<br/> You did it <a href='next'>next</a>
</div>
</body>
";
?>
You can do this in two ways:
Send the query results in the link like a GET which could be tampered with
Process the form in the same page that has your form as follows
if(isset($_POST['some_name'])) {
// Process form
} else {
// Display form
}
I got a html page with 2 forms which are using the same php script..
<?php
if ($conn) {
if (isset($_POST['form_student'])) {
if ($_POST['form_student'] == 'Send') {
if (!empty($_POST["Ime"]) && !empty($_POST["Prezime"]) && !empty($_POST["BrojIndeksa"]) && !empty($_POST["TipNastave"])) {
header('Location: forme.html');
echo "<script>alert('Processing data to sql.');</script>";
} else {
echo 'You didnt fill all fields!';
echo "<script>alert('You didn't fill all fields!');</script>";
}
}
}
if (isset($_POST['form_subject'])) {
if ($_POST['form_subject'] == 'Send') {
// same checks just like above with redirecting
// and displaying alert box
}
}
}
?>
First problem is when I don't fill all fields in, it does work and echo 'You didn't fill al fields!' but doesn't display alert box message, and it only doesn't work when I don't fill all fields. And I'm wonder how can I actually by processing php script, without redirecting to that php script page, show msg box on html page, is it possible with out ajax or jquery, or I should instead using html extension change into php, and do all checks there and avoid processing script into action=""?
That's because of the row ..
echo "alert('You didn't fill all fields!');";
Try this one instead ..
echo "alert(\"You didn't fill all fields!\");";
What you did wrong was that you had an apostrophe in the string and around the string. I don't know how to explain this but I simply made the two quotation marks to not conflict with the php echo.
Update:
Regarding the second question about the redirect and such. Could you explain it further because I don't understand a word?
I have a list of comments for a given article and I have a form underneath the comments for a user to add their own comments.
I'm using php to do some form validation.
This is the process:
User fills out form (or not) and hits submit button. page refreshes.
PHP validates user input and either submits comments if no errors or
generates a list of errors.
If errors exist display the errors.
The problem is that I want the errors to display underneath the comments before the form which it does but when th epage refreshes, the top of the page is displayed and i need it to go straight to the errors and form (much like a page anchor)
Is this possible?
This is called after the submit button is clicked
if(empty($errors)){
$result = post_comment('event',$event_id, $sendername, $senderemail, $userurl, $comment);
if ($result == 'Correct') {
//header('Location: /'.$_SERVER['REQUEST_URI']);
header('Location: '.$_SERVER['REQUEST_URI']);
}
else {
$send_error = $result;
and this is near the comments and form where i want to page to go to if errors exist
// If there was an error sending the email, display the error message
if (isset($send_error)) {
echo "<a name=\"commentsform\"></a>";
echo "There was an error: ".$send_error;
}
/**
* If there are errors and the number of errors is greater than zero,
* display a warning message to the user with a list of errors
*/
if ( isset($errors) && count($errors) > 0 ) {
echo ( "<h2 class='errorhead'>There has been an error:</h2><p><span class='bold'>You forgot to enter the following field(s)</span></p>" );
echo ( "<ul id='validation'>\n" );
foreach ( $errors as $error ) {
echo ( "<li>".$error."</li>\n" );
}
echo ( "</ul>\n" );
}
}
}
Give the form an ID which can be jumped to via the URL:
<div id="submitComment">
<!-- Comment form here -->
</div>
And then redirect the user back to the same URL with the appropriate hash tag:
header('Location: http://www.example.com#submitComment');
Find your form tag, it will look something like this
<form action='yourpage.php'>
Put a hash tag after the URL along with the anchor it will go to upon submission-
<form action='yourpage.php#commentsform'>
Using page anchors you can jump the user to any part of the page by changing the hash in the url.
Make the form send the user to to anchor like so:
<form action='yourpage.php#comments'>
And make an anchor where you want your user to end up:
<a name="comments"></a>