I have 2 pages :
page1.php :
- has a form with text box and a "submit" button. Eg : <form name="frm_register" action="page1.php" method="post">
- php and mysql code to store the value of textbox to database. Javascript will redirect the page to php2.php after the value is submitted to database. Eg :
$query = "INSERT INTO traceuser (username) VALUES ('{$username}')";
$result = mysql_query($query, $connection);
echo '<script language="javascript">window.location="page2.php";</script>';
page2.php
- mysql retrieve the data from database and display on this page.
Problem : When I press "back" button, the browser will pop up a warning message saying that the form will be resubmit. How to prevent resubmit the form when click "back" button? Is it I need to clear the cache of page1.php? How to do it with php or javascript or ajax?
Update 1 : Thanks for the answer of replacing javascript window.location="page2.php" to php header('Location: home2.php');. It fix 80% of problem. The rest of 20% problem show below :
if (strtotime($_SESSION['servertime']) < time()-3){ //10800 = 3 hours 3600 = 1 hour
if (($username != "") AND ($username != $_SESSION[username])){
$_SESSION['servertime'] = $servertime;
$_SESSION['username'] = $username;
$query = "INSERT INTO traceuser (username) VALUES ('{$username}')";
$result = mysql_query($query20, $connection);
header('Location: page2.php');
exit;
} else {
echo "same name"; //problem here
}
}else{
echo "submit multiple data too fast"; //problem here too.
}
}
The problem happen when do the following steps :
1) User submit data successfully, jump to page2.php view records.
2) User click "back" button, jump back to page1.php.
3) User submit data fail, stay on page1.php. (because too fast or same name)
4) User submit data successful, jump to page2.php view records.
5) User click "back" button, but browser shows warning message "form will be resubmited".
The problem is because of Step 3. Step 3 didn't run header('Location: page2.php');, didn't jump to page2.php. So it cause Step 5 show the warning message. How to fix this problem?
Update 2 : I have figured out the solution to fix the 20% problem, it works perfectly. I use session['error123'] to decide whether or not want to display the error message "same name". I kill session['error123'] if success submit data to database or if success jump to page2.php. I also use header('Location: page1.php'); to redirect to own page (same page) to make the page forget about form submission previously. Example of codes :
if ($_SESSION['error123'] == "toofast"){
echo $_SESSION['error123'] ;
}elseif ($_SESSION['error123'] == "samename"){
echo $_SESSION['error123'] ;
}
if (strtotime($_SESSION['servertime']) < time()-3){ //10800 = 3 hours 3600 = 1 hour
if (($username != "") AND ($username != $_SESSION['username'])){
$_SESSION['username'] = $username;
$query = "INSERT INTO traceuser (username) VALUES ('{$username}')";
$result = mysql_query($query20, $connection);
$_SESSION['error123'] = "aa";
header('Location: http://localhost/plekz/page2.php');
exit;
} else {
$_SESSION['error123'] = "samename";
header('Location: http://localhost/plekz/page1.php');
exit;
}
}else{
$_SESSION['error123'] = "toofast";
header('Location: http://localhost/plekz/page1.php');
exit;
}
}
}
Note : You need to buffer the output by <?php ob_start();?> because $_SESSION cannot put before header(). Buffer will stop all output including session, let header() send the output first.
Rather than
echo '<script language="javascript">window.location="page2.php";</script>';
you should use the header() function to redirect your user after the submission.
So in psuedo code,
click submit on page.php action page1.php
page1.php submits data to database calls
header('Location: http://example.com/page2.php');
This should prevent your clicking back problem
You can prevent the re-submission by implementing the Post-Redirect-Get (PRG Pattern).
Could be just a one-line if you've got the http_redirect function:
http_redirect("page2.php");
Instead of your javascript echo.
If not, that are two lines:
header("Location: http://example.com/page2.php");
exit;
Replace example.com with site's your hostname.
Related: Back button re-submit form data ($_POST); I am confused about PHP Post/Redirect/Get
One way is to submit the Formdata via Ajax to a remote Script and if the Query returns success you can jump the a "Thank You" Page.
So the User can hit the Back Button and the "Reload" Request doesn't pop up.
Hope the Idea helps you
Can you do it via an Ajax call instead? No action on the form, and the submit will call a the Ajax function. The Ajax call will execute the query, and provide a response (you can just echo a result), and you can then provide dynamic feedback based on the result. You'd never leave the page.
<form id="thisForm">
...form input fields...
<input type="button" onclick="return submitForm('thisForm')"/>
</form>
function submitForm(formId) {
$.ajax( {
type: "post",
url: 'page2.php',
data: $('#' + formId + ' input').serialize(),
... any other Ajax parameters...,
success: function(data) {
}
});
return false;
}
Add this code in the page that is showing as offline when the user clicks the back button:
<?php
session_start();
header_remove("Expires");
header_remove("Cache-Control");
header_remove("Pragma");
header_remove("Last-Modified");
?>
Create a Session like shown here
You should use session and validate the user from every page and you will amaze how SESSION works! AMAZING!
Related
I am using CodeIgniter.
in application/views/abc.php
<input type="text" name="company_profit" id="company_profit" value="<?php echo $form_data['company_profit']; ?>" >
in application/controller/Cde.php
$data['form_data'] = $form_data = $this->common->getOneRow("tbl_psb_setting","WHERE id=1");
if(isset($_POST) && count($_POST) > 0)
{
if($this->form_validation->run())
{
$up_data['company_profit'] = $this->input->post('company_profit');
$this->common->updateRecord('tbl_psb_setting',$up_data,"id=1");
}
}
When i click submit button, html form submitted, database record success updated. But why HTML textbox "company_profit" value is not updated? I need to press F5 refresh page then only I can see textbox value is updated.
I can see page is refresh when i click "submit" button, which mean html form submitted auto refresh page, so I guess mysql retrieve data from database assign to textbox is too fast before new record updated into database? So I try code php sleep(3); wait 3 seconds then only start retrieve data from database assign into textbox value, but fail, textbox still showing old value. Any idea?
You are fetching the data before updating it. Just move the fetch below like this:
if(isset($_POST) && count($_POST) > 0)
{
if($this->form_validation->run())
{
$up_data['company_profit'] = $this->input->post('company_profit');
$this->common->updateRecord('tbl_psb_setting',$up_data,"id=1");
}
}
$data['form_data'] = $form_data = $this->common->getOneRow("tbl_psb_setting","WHERE id=1");
Redirect back to the same page for it to get refreshed on submit.
i have form within modal after submitting form it goes on .php page. so i want to prevent this from doing this.
rather it should stay on the same modal.
below is my php code.
please let me know how to add ID of modal into header so that form will directly go onto that modal only.
<?php
include 'db.php';
if (isset($_REQUEST['insert']))
{
$contractno = $_REQUEST['contractno'];
$doctype = $_REQUEST['doctype'];
$contractdate = $_REQUEST['contractdate'];
$validupto = $_REQUEST['validupto'];
$Remark = $_REQUEST['Remark'];
$sql = mysqli_query($conn,"INSERT INTO `contract`(`projectId`, `contractNo`, `documentType`, `contractDate`, `action`, `contractValueBase`, `validUpto`, `remark`) VALUES ('".$contractno."','".$validupto."''".$doctype."''".$contractdate."''".$validupto."')");
if ($sql>0)
{
header('Location: contracts.php');
echo 'data added successfully';
}
}
?>
You need to use ajax if you want to stay on the same page, Follow the below post:
jQuery Ajax POST example with PHP
OR
If its ok to reload then use "get" method in url so that u can send the id through it and you can catch it on the page using $_GET["id"]
header('Location: contracts.php?modal_id=1'); //sending modal id via header
I have an AJAX call on a page for administrators to e-sign. When a button (adminEsign_btn) is pressed, this jQuery is called:
$("#adminEsign_btn").click(function(e){//admin esign submitted
e.preventDefault();
//validate esign
var valid = true;
if($.trim($('#adminSignature').val()).length < 3){
valid = false;
}
//action
if(valid === false){
$('#adminEsignError').html('<span class="error">You must agree to the statement and sign.</span>');
}
else{//validation passed, submit data
var schoolID = <?php echo $schoolProfile['schoolID']; ?>;
var signature = $('#adminSignature').val();
$('#adminEsignLoader').css({'display':'inline-block'});
$('#submitForm').attr("disabled","disabled");
$('#submitForm').val("Updating...");
$.ajax({
type: "POST",
url: 'bin/schoolProfile.saveEsign.php',
data: { schoolID:schoolID, signature:signature}
}).done(function(response) {
//$('#debug').html(response);
//alert(response);
if(response.indexOf('success') >= 0){//if 'success' exists in the response text
$('#submitForm').removeAttr("disabled");
$('#submitForm').val("Update School Profile");
$('#adminEsignLoader').hide();
//disable the e-sign
$('#adminAgree').attr("disabled","disabled");
$('#adminSignature').attr("readonly","readonly");
$('#adminEsign_btn').attr("disabled","disabled");
}
});
$('#adminEsignError').html('');
}
});
I didn't write the original code, so I don't know exactly what is going on in the if statement:
if(response.indexOf('success') >= 0){//if 'success' exists in the response text
But the call isn't expecting a return other than an echo of success. The following php page (schoolProfile.saveEsign.php) is what is called:
<?php
include($_SERVER['DOCUMENT_ROOT'] . '/includes/init.php');
$Page->clearance('Admin');
$Main->saveSchoolAdminEsign($_POST['schoolID'], $_POST['signature']);
echo 'success';
?>
NOTE: $Main is initialized in init.php as well as is $Page.
This code worked up until today when I tested it again. It is supposed to post the data to schoolProfile.saveEsign.php and run a function to save the schoolID and signature to a mysql database.
I've used the javascript alert() function to post the results of the "response" and it always shows the code for the entire current page (schoolProfile.edit.php).
I've run the code in Chrome and it shows that the data is being posted. It has status 302 - Found. The size is 485 B (sounds reasonable for 2 variables with only text), but underneath size in Chrome Network Debugger is content and content is 0 B - empty. I don't know if this means the data isn't being sent or what.
I've tested setting a Session variable to see if the session gets saved and I haven't been able to change it's value so that may be a sign that the data isn't actually being pushed across. But when I view the header for the page being called, it shows the 2 variables - schoolID and signature - with values.
I'm new to Chrome Network Debugger so if there are any other things I can check or if anyone has any suggestions any help would be appreciated.
EDIT: I've also tested the success and error functions inside the ajax call and success is always called. Once again it only returns the entire code for the current page (schoolProfile.edit.php).
I found the issue. In my include($_SERVER['DOCUMENT_ROOT'] . '/includes/init.php'); The init.php document redirects the user to schoolProfile.edit.php if they haven't completed filling out the school profile and it also makes sure that they aren't already at that url using PHP's $_SERVER['REQUEST_URI'].
The issue was that when trying to call schoolProfile.saveEsign.php, this url was not in the "list" of okay'd URL's so the AJAX request was always being redirected to schoolProfile.edit.php - AKA the current page. That is why I would always see the current page code when I would do an alert.
For future reference for myself. Original code:
if($_SERVER['REQUEST_URI'] != '/settings/schoolProfile.edit?f='.$Main->encrypt("INCOMPLETE")) {
header("Location:/settings/schoolProfile.edit?f=".$Main->encrypt("INCOMPLETE"));
exit();
}
Fixed Code:
if($_SERVER['REQUEST_URI'] != '/settings/schoolProfile.edit?f='.$Main->encrypt("INCOMPLETE")
&& $_SERVER['REQUEST_URI'] != '/settings/bin/schoolProfile.saveEsign'
&& $_SERVER['REQUEST_URI'] != '/settings/bin/schoolProfile.saveEsign.php') {
header("Location:/settings/schoolProfile.edit?f=".$Main->encrypt("INCOMPLETE"));
exit();
}
I looked over stack for an answer with no success. Im looking to make a form with radio buttons. Depending on the radio buttons that are checked, pressing the submit button will direct you to a different page. Right now im using php with the get option. However the best im able to do is make dynamic pages based of the get info. Any help would be great
Thanks
In your PHP you could check $_GET['radio_option'] and based on the value redirect to other pages using header function, something like this:
switch($_GET['radio_option']) {
case 'val1':
header('location: page1.php');
exit;
case 'val2':
header('location: page2.php');
exit;
case 'val3':
header('location: page3.php');
exit;
}
//here handle everything else - although normally you shouldn't get here
The other alternative would be to use javascript to set the action attribute of the form before it is submitted. For example:
$(document).ready(function() {
$("input:radio[name=your_radio_naem]").click(function() {
var value = $(this).val();
var target = "main.php";
if(value == 'val1')
target = "page1.php";
else if(value == 'val2')
target = "page2.php";
else if(value == 'val3')
target = "page3.php";
$('#myform').attr('action', target);
});
});
Another way would be to set each radio button with a value of the redirect page.
$page=$_GET['radio_buttons'];
header('location: $page');
So all i need to do is refresh a variable displayed on a php page which is stored in a MySQL db. This value is an int which is subtracted by 1 everytime the submit button from a form is clicked. As i've opted to use AJAX to post the form the page isn't being refreshed, therefore the value isn't being updated along with the form submission.
$qry = mysql_query("SELECT codes_remaining FROM users WHERE email= '".$_SESSION['email']."'");
while($row = mysql_fetch_array($qry)) {
if ($row['codes_remaining'] ==1 )
{
echo "You have ".$row['codes_remaining'].' code remaining';
}
else {
echo "You have ".$row['codes_remaining'].' codes remaining';
}
}
So this code just displays how many "codes" a person has left. I need this value to be refreshed once the submit button has been clicked from the form on the same page.
I'm using the following JavaScript to not refresh the page.
$("#form-submit").click(function(e) {
e.preventDefault();
$.ajax({
cache: true,
type: 'POST',
url: 'process-register.php',
data: $("#form-register").serialize(),
success: function(response) {
$("#output-div").html(response);
}
});
});
Thanks,
LS
If you'd like to update the value, do it like this (jQuery is easiest):
$(".submit").click(function(event) {
event.preventDefault();
$(this).load('file.php',function(val){
$('#output').text(val);
});
});
And in file.php:
<?php
connect_to_db();
$returned = get_info_from_db();
echo $returned;
?>
The jQuery will grab the info on file.php and put it into #output.
Maybe It's just me, but why not use jQuery .load function?
$("#form-submit").click(function(e) {
e.preventDefault();
$(this).load('process-register.php');
});
Maybe not ethical nor the correct way of doing this but everytime you click on #form-submit, it loads that file and therefore processes it everytime. Also note that if you load a file that uses MySQL connection yes has no mysql_connect or mysql_select_db configured, it obviously won't work. I've had that for quite some times.
In your 'success', you could possibly just throw in
$("#WhereYouWantTheOutput").load("process-register.php");
That way whenever your submit succeeds, it'll also load the output for you. Just replace #WhereYouWantTheOutput with the name of where you want the output placed.