Is there a way to check the data sent by a form to a PHP page return to the form page WITHOUT resetting the data sent and show a error?
The form has 20 fields and I need to check one of them on a bd. If it fails the user may be redirected to the form page with the form populated and displaying a error message on the field which is 'wrong'.
I would like any advice of a technique instead of populating each field using PHP.
UPDATE:
I do not want to use any solution that involves repopulate the fields by myself!!!
I want a solution that return to the form page populated with the previous values. I've tried something like js.history.back or window.back(). But the form returns empty...
UPDATE: If you are looking for this type of behavior, nowadays there are several different techniques to achive this. I'm currently using jQuery (Ajax).
In your form fields HTML, add posted values as field value.
e.g:
<input type='text' name='email' value='<?php echo $_POST['email']; ?>' />
Yeah, just check the forms beforehand, make sure you run the form HTML after the validation procedure, and if validation fails, reload the form with all of the prior information in the fields.
It might look something like this:
<?php if(isset($_POST['submit']){
// validation code goes here with a trigger variable to
// contain true or false depending on the outcome
}
if($trigger==false){
// load up your post data here
}
echo '
<!-- form HTML goes here -->
';
On your Form Validation page
<?php
$form_values = $_POST;
//Your Form Validation
//$form_validated = TRUE/FALSE; // FALSE if there were errors
if ($form_validated) {$form_values = array();}
$_SESSION['form_values'] = $form_values; /* if your form validation page and form page is not on the same page and can also use the same technique for error messages */
?>
On your Form page for each input field.
<?php
$form_values = $_SESSION['form_values']; //if your form validation page and form page is not on the same page
unset($_SESSION['form_values']);
echo '<input type="text" name="user_name" value="'.$form_values['user_name'].'" />';
?>
Different input types will need to handle the $form_values array differently but this should get your started.
If you are not using a seperate form validation page, you can get the form values directly form the $_POST array.
Related
Basically, I have my controller function for adding in my case a page but let’s focus on the function:
public function add() {
$this->session->unset_userdata('postID');
if ($this->form_validation->run() == TRUE) {
// Form Validation
}
$this->data['subview'] = 'blah blah';
$this->load->view('blah blah.php', $this->data);
}
Basically when the form is submitted it will still unset the postID in this case, however i want to ensure that if the form is submitted and there are errors that this is missed and it doesn’t redo some of my functions and variables. This is happening for a lot of my content when the form is submitted it re-initiates variables that i want to be ignored.
I also tried the following but it didn’t work either:
if (!$this->form_validation->run()) {
$this->session->unset_userdata('postID');
}
How do i avoid the entire page being redone when the form is validating as it re-performs all the page load content?
Thanks
You can check if the submit button was pushed by using
if($this->input->post('the-name-of-the-submit-button')) {
$this->session->unset_userdata('postID');
}
Basically, $this->form_validation->run() checks if the form was submitted and if it passed validation rules, whereas the above simply checks if the form was submitted at all.
You need to do an ajax submission if you don't want the page to refresh:
http://phpsblog.agustinvillalba.com/sending-forms-ajax-codeigniter/
Alternatively, you can fill in the field values so they don't "RESET", ie <input value="<?php echo $_POST['value'];?>" />, but ajax is a much better solution.
You can return errors in JSON from your codeigniter controller and display them on your page.
If you do any type of request with your browser, the page is always going to refresh, unless you use ajax/javascript.
I currently have a form which users can traditionally click on a submit button to save. The form action goes to a page called formProcess.php, which contains a meta-redirect that will save everything then redirect the user back to the form.
I have been requested to add a new feature to a hyperlink on the form page which will automatically save the form before following the hyperlink to a different page. I've currently got some simple jQuery connected to the hyperlink which submits the form like so:
$('#hyperlink').click(function() {
$(this).closest("#save_form").submit();
});
This works and submits the form, but of course formProcess.php has a meta-redirect in it which will take the user back to the form page which I don't want.
I figure if I could pass some extra parameter in the Javascript form submission, like submit('redirect=link'); then I could add something like this to formProcess.php:
if ($_POST['redirect'] == 'link') {
// Redirect 1
} else {
// Redirect 2
}
Is this possible? I can't seem to find any information on being able to pass any extra parameters using submit(); If not, what would you suggest is the best way to tackle my problem?
You can append a temporary field to your form.
$('#hyperlink').click(function() {
$(this).closest("#save_form").append('<input type="hidden" name="redirect" value="link" />');
$(this).closest("#save_form").submit();
});
In your form you can use hidden input type.
Ex.
<input type="hidden" name="redirect" value="link"/>
so when form is submit your hidden field value also to be submit with other parameter.
in your php you can simply do as below:
if ($_POST['redirect'] == "link") {
// Redirect 1
} else {
// Redirect 2
}
You can either use ajax to submit your form and upon success then redirect to the url you want.Without using ajax you could add a hidden field in your form and change it's value.Then server side you ll be able to check the value of you hidden field and act accordingly.
Say I have create a registration form. Now to add records into a DB, we send the data to another php file by POST method, where we do some validations and add a record. Is it possible to do it in the same file without sending and getting the data by POST/GET? If no, then why?
EDIT: Even sending to the same php file is SENDING and losing resource. I ask this question because I want to avoid the lost of time on sending by GET/POST and getting by the same Get/POST. And if it is not posible, I want to understand why PHP does not allow.
No. You always have to send data from the client to the server, there is no way around that.
If you dont want to reload the entire page the user is on, you could submit the data via AJAX to the php file responsible for processing it and adding the data. That way the user never leaves the page.
yes ofcourse.
just in your form "action" put
$_SERVER['PHP_SELF']
then in the beginning of your PHP page check if the $_POST is set or not
if(isset($_POST))
{
// actions to be taken after form submission
}
ofcourse you can add a hidden input tag for refining checks for the $_POST. eg in your form
<input type="hidden" name="formSubmit" value="yes" />
then your check should be like
if(isset($_POST['formSubmit']))
{
// actions to be taken after form submission
}
It's possible. For example:
<?php
if(true === isset($_POST['submit']) // check if submit-button was clicked
{
// do some validation here...
// If validation successes add record into db here...
}
else // no post data sent so output the form
{
// output the form here...
}
Yes it is possible set
action="same page"
in form tag.
you can access your all form attributes on same page.
Yes it is easy. The form can post back to its self. This is most easily done by not even specifying the value of action in the form tag.
<form method='POST'>
Then at the top of the page before any content is put on the page, include an if statement to check if the form was submitted.
if (isset ($_POST['post'])) { // 'post' is the name of the submit button
$error = false;
// Do validation
From there do validation and act according to the result.
If you have lots of validation to do, perhaps put that in another file and include it.
include "formValidation.php";
If all is well and all tests are passed use
if ($error === false) {
Header ("Location: confirmation.php");
exit;
}
}
If tests fail, stay on the page keeping all the post data, and display an error.
if (isset ($error) && !empty ($error)) {
echo "<div class='error'>$error</div>";
}
I have an HTML form. Let's say I fill out all the fields and submit it (PHP script runs here).
Then I want to go back to the form using "Back" button of my browser.
What I see is the empty form.
What do I do to have the entered data retain on the page after I come back to it using "Back" button of the browser?
Thank you!
If you use the "Back" button of your browser then your browser is responsible for re-populating your form data.
Usually that functionality is handled by the browser, however if you want to "force" the fields to always be pre-filled with the user's data, you can store the $_POST data in a session variable and use that to load the form.
Example:
// submission page
session_start();
if(isset($_POST)){
// save the posted data in the session
$_SESSION["POST"] = $_POST;
}
Then on the actual form page, you can check to see if session data exists. It won't if the form is being loaded the first time, but it will if the user submits the form and then presses the browser back button:
// form page
session_start();
if(isset($_SESSION["POST"])){
// previous POST data has been saved
// build the form with pre-defined values from $_SESSION
...
} else {
// no previous data
// build the form without pre-defined values
...
}
Note that you must call session_start() before outputting any HTML.
Store the value in a session
session_start();
//form so that you have all the potential forms in a single session array
//form_1 to identify the form in question
if(!empty($_POST)){
$_SESSION['forms']['form_1'] = $_POST;//if this is for the public internet, then I would really consider making sure that the posted data matches the received data... (and that its comming from YOUR form), which is way too long to post here...
}
then on the form page
<input name="flowers" value="<?php echo if(isset($_SESSION['forms']['forms_1']['flowers'])){ echo htmlspecialchars($_SESSION['forms']['forms_1']['flowers']);} ?>" />
obviously the above can be simplified, but for a example's sake it's better this way.
(make sure to clean out the old form data eventually)
You can potentially store the data in the session, and re-populate it back using PHP sessions. You should create a separate back button that takes you to the previous page.
Example:
Storing data:
$_SESSION['data'] = $_POST['item1'];
In the HTML Forms:
<input type="text" name="someinput" value="<?=$_SESSION['data']?>" />
I have several forms inside DIVS on my page.
I have one form which contains a text field and is always visible, and this is where the user hits 'enter' key and submits...
I want to get values selected in the other forms on the page, and submit them all together, not one by one, so that my PHP code can use "ALL VALUES" and search a mysql database...
Is this possible by javascript using the "<form onsubmit>" to call a javascript?
any codes would be appreciated...
thanks
Without some Javascript hocus-pocus, you can't. One form = one request.
You can do it with JS, and you have a few options. The easiest would be to loop through all the forms on the page, and basically duplicate all the input fields and values into one form and then submit that combined form.
With jQuery it'd go something like this:
$("form").submit(function() {
combineAndSendForms();
return false; // prevent default action
});
function combineAndSendForms() {
var $newForm = $("<form></form>") // our new form.
.attr({method : "POST", action : ""}) // customise as required
;
$(":input:not(:submit, :button)").each(function() { // grab all the useful inputs
$newForm.append($("<input type=\"hidden\" />") // create a new hidden field
.attr('name', this.name) // with the same name (watch out for duplicates!)
.val($(this).val()) // and the same value
);
});
$newForm
.appendTo(document.body) // not sure if this is needed?
.submit() // submit the form
;
}
You need to make a script which will collect the data from the forms, and inject them into the only form that is visible. Only one form will be submitted, you can not submit multiple forms.
You can create multiple hidden fields, or you can construct a single hidden field in that form, then use javascript to collect all the data from the various forms, then create a JSON string, set the value of the hidden one, and submit.
Edit:
Say you have a single hidden input like this:
<input type='hidden' name='hiddenfield' id='hiddenfield' />
you could use JQuery to do this:
$('#hiddenfield').val('myvalue');
To get the value from other forms is as simple as calling $('#elementid').val()
before form submission. To use JQuery, go to the jquery website, download the library, and link it (follow their installation guide).
you can add an onsubmit to that form, and then collect other values with javascript:
<input type="hidden" name="hidden1" id="hidden1" />
<input type="hidden" name="hidden2" id="hidden2" />
<script>
document.getElementById("the_form").onsubmit = function(){
document.getElementById("hidden1").value = document.getElementById("other-field1").value;
document.getElementById("hidden2").value = document.getElementById("other-field2").value;
};
</script>
Wrap the whole Page in your form tag (if possible) and use the server side code, along w/ Javascript, to handle your business rule validation.
kind of a hack solution, but it should minimize the necessity for Javascript "hacks" depending on your skill level with javascript.