Form refresh after submit - php

The form below can contains different elements of text fields, drop down and selection boxes, which allows the user to update his profile. The process of updating MySQL fields is being done after form submits.
<form method="post">
My Name: <input name="myname" type="text" value="<?php echo $_SESSION['SESS_MY_NAME']; ?>" /><br />
My Email: <input name="email" type="text" value="<?php echo $_SESSION['SESS_EMAIL']; ?>" /><br />
<input type="submit" name="Submit" value="Update" />
<?php
if (isset($_POST['Submit'])) {
// MySQL update
;
;
;
$result=mysql_query($sql);
}
// if successfully updated, make form refresh.
if($result){
;
;
;
}
?>
</form>
I want to refresh only the form, so that the user will stay in the same page and will see the changes that he made (i.e. What do I need to put under the comment in the code “if successfully updated, make form refresh”?).
I cannot use header("location: samepage.php"); because I have too many HTML codes involved in between and before.
Appreciate any help,

Move the isset($_POST['submit']) check to the top.
Your current (intended) process is as follows:
Retrieve form data from DB/Session/etc.
Display as HTML
User submits form
Repeat steps 1/2
Write data to DB
Force refresh
Repeat 1/2 again
If you move this check to the top, the process is changed to:
Retrieve form data from DB
Display as HTML
User submits form
Write data to DB
Repeat 1/2 (it will now retrieve the updated information and display correctly).
This is the absolute simplest way you can do it. It doesn't take into account Post/Redirect/Get or updating the session so multiple DB reads are unncessary, etc.

Why don't you use jQuery AJAX to submit and verify the form then output the result in chosen div element.
More on that available at nettuts+

Such helpful. Much wow.
Thankfully I was able to solve this on my own after some intense googling since no one else seemed to have an answer. For anyone looking to accomplish the same thing, all you have to do is add the following code to the "Additional Settings" section of your CF7 form configuration:
on_sent_ok: "location = 'http://domain.com/contact';"
Just replace the URL with the URL of your form page and presto, it'll automatically refresh back to that page when the form is submitted!

Related

How can a submit button made to be act as a link too?

I'm doing a Quiz project: The idea is to implement almost 25 questions in which each question occupies each HTML page with 4 radio buttons and a submit button and a reset button as well.On clicking the submit button it should take the user to the next page as well as submit the data to the server. How to achieve this dual behaviour?
I tried this:
<form action="cba.php" method="post">
<a href="abc.html">
<input type="submit" value="submit">
</a>
</form>
But this does only one purpose: Acting as a link without submitting the data.
If you just want to redirect the user after submitting the form, you can use :
header("Location: yourlink");
in the php script you called cba.php.
Otherwise, i'm not sure it is possible to redirect the user before sending him the php script page.
As mentioned, it would be a smoother experiance to handle this via ajax, but it can be acheived in just php by creating a redirect in the form processing code (as mentioned in comments and a current answer).
I believe your issue is with the fact that the same proccessing code (cba.php) will be called every step of the way, so you need a way for each quiz section to define the next section.
This can be done with a hidden field instead of the link code you tried:
<form action="cba.php" method="post">
<input type="hidden" name="next-page" value="abc.html">
<input type="submit" value="submit">
</form>
Then i cba.php, you redirect to the value contained in this hidden field:
//save the data from the form, then
header("Location: " . $_POST['next-page']);

PHP and html post button value

I have a html page where the user can input some text, it is then posted to a php file and then stored in a database.
<form action="postphp.php" method="post" enctype="multipart/form-data">
<center><input id="postTitleStyle" type="text" name="title" size="100" maxlength = "180" ></center>
<center><textarea id="postTextStyle" name="Text" rows="10"cols="96" maxlength = "40000"><?php echo $text;?></textarea></center>
<center><input id="postTagStyle" type="text" name="tags" size="100" maxlength = "900" ></center>
<center><input type="submit" class = "Post2" value="post"></center>
</form>
Above is my current code for posting the data in the text field to a php file. I want to be able to click a button that when clicked will not go to the php file it will be stored and then when the user clicks the submit button it is posted. For example the user clicks it, a one is stored and then sent later when the user clicks the submit button after they are finished filling in other details. Is this possible?
P.S. I want to avoid Javascipt as much as possible for the moment, so if there is a non-java way of doing it then it would be much appreciated.
Many thanks, Jack.
There are two easy solutions to this problem without using Javascript. I'm assuming by your wording that you can currently post a form, but you don't know how to do so without leaving the current page. That's what I'll be answering below, but please note that there is no way to post a form without reloading at all without Javascript.
Solution 1: Put the PHP code into the same page the form is on and change the form tag to: <form action="" method="post" enctype="multipart/form-data">
A blank action field will cause it to run the PHP on the current page. You will likely need to look into using isset($_POST['submit']) in PHP, which will check whether the submit button has been clicked on before running that particular PHP code. You can read more about that HERE.
Solution 2:
In the postphp.php file that's currently linked to in your action field of your form, you could use a PHP header that will redirect the user after the PHP code is ran.
E.g.
<?php
{All your form processing code goes here}
header('location: my_form_page.php');
?>
In this example, my_form_page.php is the page on which your form is on. You can read more about headers in the answer of THIS question.
Hopefully this helps a bit.
$title = $_POST['title'];
$text= $_POST['text'];
$tags = $_POST['tags'];
mysql_query("INSERT INTO `table_name` (`colname1`,`colname2`,`colname3`) VALUES ('$title,'$text','$tags')");
$id = mysql_insert_id();
if($id){
echo "inserted";
}else{
echo "Not inserted";
}
For this you need to use Ajax (JavaScript will be used) because you need a button which send data to server without form submission and page reload it can be easily achieved using Ajax.

load form using AJAX will loose form and values after a failed submission

I have a PHP page that loads several parts of a form using AJAX. For instance, first check if the user is already registered, if so the script loads (with AJAX) the rest of the form. The form will not be submited using AJAX what can be a problem when the user submits the form (without AJAX) - imagine there are some errors - the form will loose all values.
I'm wondering if CSS hiding part of the form and after the successful login use JS to display the rest of the form, would be better.
Here some code:
<form action="some_action.php">
Email: <input type="text" name="email" id="email"> <br />
Password: <input type="password" name="password" id="password"> <br />
<button id="vrf_login">Verificar</button>
<div id="rest_form">
</div>
</form>
AJAX:
- CHECK login: if email and password matches then
- LOAD the form for div with id "rest_form"
(it is in another file, for instance:
<input type="text" name="place" id="place">
<input type="text" name="age" id="age">
<input type="submit" name="submit" value="submit">
)
The problem is if I submit the form (without AJAX) and there are errors I will loose the form loaded with AJAX
EDIT (again)
Thank you all for your constructive suggestions:
The solution I adopted is close to the first Alkis's suggestion:
almost all the form is hidden (CSS)
after some logic choices the (part of the) form is turned visible (jQuery) - to "remember" what parts should be visible in case of submission failed (server side validation) some session variables hold the information (AJAX) - and then, after the submission (failed) use jQuery to restore the prior form structure (get the session variables with JS this way: var xpto = "<?php echo $_SESSION['prior_xpto']; ?>" ; )
the fields of the form will remember theirs values (with PHP)
You have 3 options.
Stop loading the whole form by ajax. Hide it with css and show it if the the conditions are met. If the page is shown after some validation error, just show it (change the css inline or give it a different class)
Have a condition and every time the page loads check if it is a first load or if the page is shown after some validation error occured. If the latter is true then load again the form with ajax. This condition can be a hidden field that takes its value from the server and you check it on the client every time you serve the page.
The second solution can be done on the server too. Have the condition be checked on the server. If it's a first load, then don't populate the form and let it be populated from ajax as you do now. If it's after a validation error then pre-populate the form. It's just an if/else clause.
Please provide some codes for your question, but i guess your problem is sending result using a button with "submit" type !
if you have a form like this:
<form>
<inputs ...>
<input type="submit" value="Send data" onclick="SendDataUsingAjax()" >
</form>
after clicking on submit all values on input will reset regardless of what your ajax function is doing. to fix this problem you only need to change type="submit" to type="button".

HTML form insert in SQL DB and also pass posted vars to page

I have come across a situation I am not sure how to hndle. I am new to this, but I do understand the server side realm of php vs user side of the browser.. I just dont know how to accomplish what I want to do..
I have a form on a page where a user can enroll in a school course. They select the course type, location, date, and payment type.
On submit it goes to an outsourced shopping cart for payment, which uses PHP vars to populate the item description, price, ect.. along with our store id and other pertinent information.
I ALSO need to insert some of the PHP vars into the user database.
I tried having the form action go to another PHP page which process the DB entry then redirects to the cart, but when I get to the cart an error is generated saying the info was not submitted properly.. but the DB entry was successful.
I also tried using an include(dbentry.php) in the form action with the cart link.. this generates a server side error on loading the page.
At one point I successfully had it create a db entry (although it was blank) AND successfully redirect to the cart with all of the vars there, but a blank DB entry does me no good. I am assuming entry happened before the $POST vars were created... I also have changed so much I dont remember how I did it and cannot reproduce that..
My main question is:
How can I have a user fill out an HTML form, and when submitted perform the DB entry with the $POST vars while also directly passing the $POST vars to the cart page? Normally I would run the dbentry.php on the next page, but I have no access to scripting on the outsourced cart page...
You can try to use hidden textboxes to hold the values of the form! And this value can be accessed from different php pages
You will need to pass your variables from page1.php to page2.php to outsourced cart. I would do something like the following:
What the below code is doing:
Send original form data using POST to page2.php
Page2.php will then read the POST data (you can now do what you want with this data, whether it be store it into a database, etc.). A Javascript snippet will then submit the form to your checkout cart page (page3.php) with the necessary POST variables which are being stored as hidden fields within the form.
Page1.php
<form action="page2.php">
<input type="text" name="myfield1"/>
<input type="text" name="myfield2"/>
<input type="text" name="myfield3"/>
<input type="hidden" name="myfield4"/>
<input type="hidden" name="myfield5"/>
<input type="hidden" name="myfield6"/>
<input type="hidden" name="myfield7"/>
<input type="hidden" name="myfield8"/>
</form>
page2.php
<?php
if(isset($_POST['myfield1']))
{
$myfield1 = $_POST['myfield1'];
}
// do the above for all of the fields, use the data to query database with.
// Perform database operations here
?>
<form action='Page3.php' method='post' name='frm'>
<?php
foreach ($_POST as $a => $b) {
echo "<input type='hidden' name='".$a."' value='".$b."'>";
}
?>
</form>
<!-- Script to submit button -->
<script language="JavaScript">
document.frm.submit();
</script>

redirect to current page if user clicks back or refreshes the page

Sorry I have posted this question and I googled it alot still Im unable to solve this
I have a php page that has a form and when user clicks refresh or F5 it creates duplicate values in the database and also a message is alerted to the user, indicating resubmitting may insert duplicate values in database.My boss dont want that alert box of the browser to user and also insertion of duplicate values into the database
I know its header(). I read lot of header() in php manual and also server_name functions but still I tried in many ways putting in the top but cant solve it. its very important. can anyone please help me with a sample of code explaining the way to do.any help is greatly appreciated.
<form method="post" action"demo.php">
<input name="fname" type="text">
<input type="submit" value="submit">
</form>
demo.php
<?php
$firstname = $_POST['fname'];
?>
Tell me what should i add in the demo.php page to stop it from submitting the form again and again and also if user clicks back button on the browser it should not direct to the previous page , it should still redirect to current page.
So if user clicks refresh or back button it should redirect to current page only and should not insert any duplicate values and also alert box should be disabled.Please explain me what to do here, im in deep help.Thanks
There's lots of things wrong with your code, and lots of ways to mitigate the impact.
First, why are you creating duplicate entries?
In addition to the problem of bad data is also implies that your site is vulnerable to CSRF. Go read up on how to prevent CSRF with single-use tokens.
If you've got performance problems with your site, then users will often click on the submit button multiple times. While addressing the duplicate submission problem on the database, use javascript to disable the submit links on the page and provide visual feedback that the page is doing something.
Redirects are not the way to solve the problem.
My boss dont want that alert box of the browser
Are you talking about the duplicate post alert? While you can get around this using PRG, that creates other problems.
You must post a unique id (session_id) and save it in the database.
When your registration, test if the session_id is already present. If so, send a message to THE USER. "You have already post out this form"
The code:
<?php session_start; ?>
<form method="post" action"demo.php">
<input name="fname" type="text">
<input type="submit" value="submit">
<input type="hidden" name="session_id" value="<?php echo session_id();?>">
</form>
demo.php
<?php
//test session_id in database
$session_id = session_id();
mysql_connect('localhost','xxx','xxx');
mysql_select_db('xxx');
$return = mysql_query("SELECT COUNT(*) AS nb_data FROM TABLENAME WHERE session_id='".session_id()."'");
$data = mysql_fetch_assoc($return);
if ($data['nb_data'] == 0){
echo 'Your message';
}
else{
$firstname = $_POST['fname'];
//.....
header('location:xxx.php')?
}
?>
I would use php header function to replace the current location so if the user clicks refresh, it won't repost the information and a session to store the posted value and check for resubmissions.
demo.php
<?php
session_start();
if($_POST)
{
if(!isset($_SESSION[fname]))
{
//database queries here
}
$_SESSION[fname] = $_POST['fname'];
header('location:demo.php', true); //true replaces the current location
}elseif(!issset($_SESSION[fname])){
header('location:form.php');
}
$firstname = $_SESSION[fname];
?>
form.php
<form method="post" action"demo.php">
<input name="fname" type="text">
<input type="submit" value="submit">
</form>
You need ON DUPLICATE KEY , this will update the record instead of creating a copy of it :
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
so it wouldn't matter if they hit refresh or resubmit, if the record existed already it would just get updated.
The solution will be to redirect the page after database operations like insert, update and delete
pageName: test.php
if(isset($_REQUEST['deleteBtn']))
{
$emp_id=$_REQUEST['emp_id'];
$count=mysql_query("delete from employees where emp_id=$emp_id");
header("location:test.php");
}
This way if you click F5 or back button the form data will not get posted again.
What you want is to embed a session id in your form when you create it, and to track that session id on the server. Then, when the form is submitted and you are processing the form on the server, if the form was submitted more than once, you can overwrite the first submission in your database, or respond with an error message, or whatever. (Show the popup only on the first submission, whatever.)
An easy way to do this is to generate a session id, send it as a hidden field in the form, and when the form is submitted store the session id in your database with the constraint that the session id be unique.

Categories