echo '<td><input type="text" name="input"></td>';
echo '<td><input type="button" onclick="function(input.value);"/></td>`;
written in php. it's all in a table which is in a form. The function is executed properly, sends the data into a new php file and is running some data validation tests displaying some (error) messages according to these test results.
if the input is correct, i want the code to insert the value into a database and refresh the whole page. The data is being inserted, but the page is not refreshed.
I use this at the end in order to refresh but it doesn't seem to work:
echo '<script type=text/javascript language="javascript">document.location.href="page.php"</script>';
So you send some data back to an php file and in the event that some conditions are not met you send back some error messages, in the case they are met, cant you just simply use:
header( "Location: page.php");
exit;
Related
I have two simple HTML form buttons that call PHP functions to send emails now. Everything works fine except for one thing. If one of the buttons is clicked to send a report, and then the page is refreshed, the function seemed to be called again and the emails well go out again with a page refresh by a user using a browser refresh button.
If the page is refreshed, the email will go out again for the last button clicked. So, if I click on Button 1 and then refresh the page, I will get two reports for button 1. If I click on button #1, and then click on Button #2, only the second report will go out. If I click on button #2 and then #1, only Report #1 will go out again.
So, no matter how many buttons are clicked, refreshing the page will cause the last button click (only to repeat). Trying to unset the request parameter (in code below) has no effect all on the repeats caused by a page refresh.
I don't understand why (on a Page Refresh) the page is seeing the last button click made as set, and why the unset command is not working.
Thanks for any help.
if( isset( $_REQUEST['email_this_weeks_report'] )) {
unset($_REQUEST['email_last_weeks_report']);
#send email now email code for this week
}
if( isset( $_REQUEST['email_last_weeks_report'] )) {
unset($_REQUEST['email_last_weeks_report']);
#send email now email code for last week
}
<form>
<input class="ui-button ui-widget ui-corner-all" type="submit"
name="email_this_weeks_report" value="Email This Weeks Report Now" />
</form>
<form>
<input class="ui-button ui-widget ui-corner-all" type="submit"
name="email_last_weeks_report" value="Email Last Weeks Report Now" />
</form>
Clicking the button submits the form.
The data in the form is bundled up and included in the request.
Aside: You're using method=GET, the default, but you're not making a "safe" request. You are doing something, not just getting information. You should use a POST request.
When you click refresh, you tell the browser to make the request again and display a new version of the page.
Since the request includes the query string which says "send a particular email", it sends that email again.
Unsetting values in $_REQUEST has no effect because when the browser makes a new request with the same data in it: $_REQUEST just gets filled up again.
You should deal with this by using the PRG pattern:
Submit the form using method=POST
Have your PHP script process the data in the form (i.e. send the email) then redirect to a different PHP script
Have the new PHP script display the result (in this case there is no result, its just the form, you could use a plain HTML document with no PHP in it).
Change
<form>
To
<form method='POST'>
A simple way to prevent multiple submissions is to add a random token to the form in a hidden input.
<input type='hidden' name='formtoken' value='<?= uniqueid() ?>'/>
Every time the page is fetched from the server, the value of this hidden variable will change. So on the server side, you can prevent the same form being resubmitted by checking whether a form with this unique ID has been submitted before.
session_start();
$sessionToken = $_SESSION['formtoken']? : null;
$currentToken = $_POST['formtoken']? : null;
// If no session token yet: form has never been submitted
if(!$sessionToken):
// save the current token in session so we'll recognize it next time
$_SESSION['formtoken'] = $currentToken;
/* ok to send the email */
// ElseIf current token was already used: Duplicate form submission
elseif($sessionToken === $currentToken):
/* don't send the email!*/
// Else session token exists, but current token is new: User fetched a new form from server
else:
// update the session token
$_SESSION['formtoken'] = $currentToken;
/* ok to send the email */
endif;
When the user refreshes, the browser will ask if she wants to re-submit the form. If she does, you will know because the current token and the session token will be the same. It's up to you to decide how to handle it.
Refreshing a page with a GET or a POST form will resubmit the data (albeit it will ask you first in the POST scenario, which you should use by the way).
Try redirecting the user after form submit
if( isset(...) ){
// Do your logic
header('Location: https://you_site.com/your-form-page?thank-you');
exit;
}
This must be done before anything else is outputted on the page.
i am trying to make something related to paging, where i have a array of around 400-500 values..
i want to show 9 values at a time and then after clicking on NEXT button i want to show next 9 more..
Here is the part of the code i am using to call JS function onclick of button and that function's job is to get the count from the browser and set it to next value.
<?php
session_start();
$_SESSION['count']=9;
echo "<script type='text/javascript'>
function changelistnext()
{ ";
$c=$_SESSION['count'];
$c=$c+1;
$e=$c+9;
$_SESSION['count']=$e;
echo "
alert($c)
alert($e)
}
</script>";
?>
<button id='next' value='next' onclick='changelistnext()'>Next</button>
But everytime i click on the next it shows the same value....
You can't mix JavaScript and PHP as if they were one and the same.
JavaScript is a client-side language, which is executed in your browser.
On the other hand, PHP is a server script, and sessions are also kept on server.
If you open your page's source code in a browser, you will see that the session stuff is not there - it was executed by PHP when the page was generated. You can't use sessions directly in JS.
The page contains essentially this:
<script type='text/javascript'>
function changelistnext()
{
alert(some number) // value of C when the page was generated on server
alert(some number) // ditto for E
}
</script>
You could use Ajax call to ask some script on your server to give you data for the next "page" - PHP script can access the Session variables and send what you want back to the browser.
I am making a page that has a bunch of fields that allows the user to enter in information and submit it to a database. This page is called 'add.php' I created a 'form' tag and had the information posted to another page called 'process.php' where the information is collected, then inserted into the database. I want the user to know whether it was successful or not, so I was wondering how to tell the user something specific on the 'add.php' page. like "insertion successful!" at the top of the page.
I thought of including the 'process.php' code in 'add.php', then calling the 'add.php' in the action of the form, but the code gets called the first time the page is loaded, which inserts a completely blank entry into the database.
Should I implement some sort of flag that is only set to true after the 'submit' button is clicked? Or is there another way to update the page and tell the user the status of the insertion?
I can paste the relevant code as needed. :)
Thanks!
Assuming that you are using the post method in your form and php, you can simply check if a post was made:
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
// form was posted, process and display output
}
else
{
// nothing was posted, normal get request, show form
}
just check if query worked well. If no exception was thrown, it mostly has, and the add appropriate message with output.
First you need to check and handle errors
try
{
}
catch(Exception $e){
header('Location:oldlocation.php?succ=0')
exit();
}
header('Location:oldlocation.php?succ=0')
exit();
If all goes well, you can also redirect to a new location(as shown in code). This has to be done properly, you may redirect back to the old location, with additional data like
oldlocation.php?succ=1;
If anything goes wrong redirect to
oldlocation.php?succ=0
Then fetch the succ using $_GET["succ"] and print appropriate message.
If you din get, comment.
Here's what I would do...
Keep your processing data in one file, and include the form file at the end
//add.php
//if the form is submitted make the database entry
if(isset($_POST['foo']) AND $_POST['foo'] != '')
{
//code to process form submission
$success = 'success!';
}
//include the form
include addform.php
in addform.php put your form. Include an 'isset' that is watching for $success to alert that the entry was successful
//addform.php
<?php if(isset($success)){ echo "<h2> Data successfully entered! </h2>";} ?>
<form action='' method='POST'>
<input type='text' name='foo' />
//etc
</form>
So once you submit the form, the code starts at the top of add.php - the 'isset' sees the $_POST submission, runs the form submission code and sets the success variable. Then, it includes the form page. The form page has an 'isset' that is watching for the success variable. When you first navigate to the page, or if you refresh, the add.php code will skip the first code block (the form submission stuff) and won't make a database submission or set the success variable.
I have a basic form that asks for certain information and then validates the form using javascript before actually submitting it to a seperate php file to email the form submission to me however, after successfully submitting the form, it goes to blank page and then a Thank you popup shows up. How do I set it so hitting the submit button doesn't go to a new page but just displays the popup on the current page?
My code for filling out the form is:
<form action="send_group.php" method="post" onsubmit='return formValidator()'>
//Asks to input information
<input type="submit" value="Submit" />
</form>
My PHP code is:
<?php
$webmaster_email = "email#email.com"; //E-mail the message will be sent to
$info = $_REQUEST['info'] ;
$info1= $_REQUEST['info1'] ;
$info2= $_REQUEST['info2'] ;
$info3= $_REQUEST['info4'] ;
mail( "$webmaster_email", "Information Form Submission",
"Info: $info
Info1: $info1
Info2: $info2
Info3: $info3" );
echo "<script type='text/javascript'>\n";
echo "alert('Thank you for your booking request. We will get back to you as soon as possible.');\n";
echo "</script>";
?>
You have to use an AJAX request.
So you bind an onclick event on your submit button, then you send an AJAX request, and when the AJAX request suceeded you display your response (Bad or not).
JQuery is really powerful and easy for AJAX request, look here : http://api.jquery.com/jQuery.ajax/
You can either use AJAX to submit the data in the background, or, the easier option put the from and php into the same php file.
Well, the browser shows exactly what it receives from your php-script.
One way to solve your problem without Ajax could be the following approach: To display your original page after the request has been processed add e.g.
header("location: your_form_page.php?req=1");
in case of success, and e.g.
header("location: your_form_page.php?req=-1");
in case an error occurred to send_group.php. The GET parameter req can be used to display either the thank-you-box or an error message. The switching logic must of course be implemented already in your_form_page.php, e.g.
if ($_GET['req'] == '1') {
echo "<script type='text/javascript'>\n";
echo "alert('Thank you for ...');\n";
echo "</script>";
} else if ($_GET['req'] == '-1') {
echo "<script type='text/javascript'>\n";
echo "alert('Error ...');\n";
echo "</script>";
}
You have to redirect the user after the script successfully finishes, using the location header
header("location: formPage.php?success=1");
Then on your original form page you can run the javascript.
Use xhrRequest (ajax) for retrieve information from validation page and then show result to your user.
I have a questionnaire in a form. In the end of it the submit button is pressed that is supposed to call a .php file that inserts data into a database through its action information and afterwards show the last page that contains something like "thank you for participating etc." via the onsubmit info.
problem is that the last page is shown before the .php file is shown which means it is visible only for like half a second and then the php script is carried out which ends up showing a blank page.
The php script works it inserts data into the questionnaire correctly so there should be no mistakes syntax-wise.
any ideas if I have to exit the cript or something and return to the .html file or what could be wrong?
on your opening form tag add action="submit.php"
then once it goes to that page when the submit button is hit add this to the bottom of that php page:
header("Location: successfull.html");
IT sounds like what youre doing is showing the message with Javascript via the onsubmit event - this happens before the request is even set to the server and the php script. Youd either need to do an ajax form submission and then display the message when the request completes or make the php script redirect to the success message page when it is done.
But this is all just speculation without seeing any code... you should post some :-)
Why not submit the form to process.php then process it:
if(isset($_POST)){
$name = $_POST['name'];
// etc etc
// if all error checks pass, then echo out - thanks for taking part in our survey!
}
What you're doing is submitting it, and it seems you're getting javascript to say 'thank you' but it is being submitted before this thank you message can be displayed - no harm in echoing this out on your .php page!!
Update
You mention about redirecting to a page afterwards, but this can be done by:
header("Location: where/to/go.php");
exit;
But you can't do this with the above (echoing out a success) since it will redirect straight away.
The way I deal with this is putting the html contents into the php file.
<?php
if (!isset($_POST["submit"])) { // if page is not submitted to itself echo the form
?>
<html>
<head>
<title>survey</title>
</head>
<body>
<form method="post" action="<?php echo $PHP_SELF;?>">
...... (your form) ......
<input type="submit" value="submit" name="submit"><br />
</form><br />
</body>
</html>
<?
}
else {
$db = new PDO('...');
$db->exec(...);
echo "Thank you!";
}
?>
A few ways you could accomplish that.
You could make the php file it submits send out the data for the "thank you for participating" page (if you're fine with simply going to another page).
Alternatively, if you want to stay on the same page but just show the "thank you" notification, I would use JavaScript to disable the default action (e.preventDefault(); in the event handler) for the "submit" button on the forum, then also use JavaScript to use AJAX to submit the data.
An example (using JQuery), which won't change your page and perform the submit in the background, and display the "thank you" when done, on the current page.
$("a#confirmSubmit").click(function(e) {
e.preventDefault(); // Prevents the submit button from changing pages
data = {
Name: $("input#Name").attr("value")
// Add other data here also
};
$.post("/page/to/submit/to.php", data, function(d) {
//Write the code here to show the "thank you" notification.
//It will show upon completion here.
});
});
If you want to check for errors with inserting into the DB, you could check the value of the data of the AJAX call, to conditionally show the error. You can then return the user to the exact same form they were already on, with all the data still there, and show them an error message.