remove form validation errors with a page refresh - php

I have a page that takes form input, it is written using HTML and PHP(codeignter framework), the issue I am facing is when there is a form validation error, the page refresh is not reloading the page like brand new, I mean its not clearing the input from fields and the error message still coming up on page refresh and even after I correct the input and hit submit, when I click browser back button the it is still loading the page with validation error..
Any idea why it happens or how to resolve it. I just need the page to reload when I refresh it.
Here is my view (view1.php)
<html>
<?php
echo validation_errors();
form_open('search_controller/search_fn');
form_input('input1', set_value('input1'));
form_input('input2', set_value('input2'));
form_input('input3', set_value('input3'));
form_submit('submit', 'Submit');
?>
</html>
Controller Functions
function index() {
$this->load->view('view1');
}
function search_fn {
if($this->input->post('submit') {
$this->form_validation->set_rules('input1', 'XXXX',
'trim|some_validation');
$this->form_validation->set_rules('input2', 'XXXX',
'trim|some_validation');
$this->form_validation->set_rules('input3', 'XXXX',
'trim|some_validation');
if($this->form_validation->run() == FALSE) {
//when validation fails
$this->load->view('view1');
} else {
//when all input is validated sucessfully
do some processlisng,
//load some other view
$this->load->view('view2');
}
} else {
//When page is refreshed, this is supposed to redirect
redirect('search_controller/index');
}
}
when the input validation fails, the url comes back as www.something.com/search/search_fn and when I refresh, it basically loading the same page with same error message. I, somehow, need to reset
the $this->input->post('search'), so that it will be true only when the search button is clicked.
Thanks.

Are you using CodeIgniter's redirect() function after processing form? you should always do that
I mean after you are done handling submitted data, instead of return TRUE or simply closing function, to a simple redirect('CONTROLLER_NAME'); even if you want them to be on the same page
As for the fields, i would suggest using autocomplete="off" in your inputs (if you are not using an <input type="text"> above an <input type="password"> because Chrome and next version of Firefox will ignore automplete="off" in that situation)

Related

Show validation errors in FancyBox in CodeIgniter

I have a FancyBox in the home page which contains a registration form.
Validation is working fine.
Currently, I have to manually click on the FancyBox to see the error messages on that form.
Here's the code which reloads the page. But I want it to show the FancyBox as soon as the page loads. It is just a simple validation check.
if ($this->form_validation->run() == FALSE)
{
$this->load->view('valform');
}
else
{
$this->load->view('formsubmit');
}
So what I want is to show that FancyBox with validation errors.
Validation is working, as it is shown in the FancyBox; when the page reloads I have to manually click on that FancyBox to see the validation errors. Is there a way I can store it in a session and use that instead? If yes, how? Or how can I use ajax for this, and get validation errors to show on the FancyBox?
You can see the example below. Try to implement it with ajax and jquery.
public function ajax_()
{
$this->form_validation->set_rules('par','name of something','required');
if($this->form_validation->run()!=TRUE)
{
echo json_encode(array('result'=>'error','msg'=>validation_errors()));
}
else
{
echo json_encode(array('result'=>'success','msg'=>'success'));
}
}

Codeigniter controller prevent entire page from reloading when form is validating

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.

Codeigniter redirect does not update url using jQuery mobile

I have a login controller, which is suppose to redirect to my index page when the user is valid. The redirect works, but at the index page the url is still that of the validation method ex: login/validate_login/. If i click on a link on the index page, and then try and go back in the brower history, the browser points me to the validate method and not the index page.
How do i fix this?
I have tried using redirect with both refresh and location, but both with no luck.
I suspect this is a problem with the ajax call of jQuery mobile, but i'm not sure.
Any help appreciated.
Kind regards
NOTE: I would post an image of the url at the index page, but i'm not allowed to because i'm a new user.
My validate method:
function validate_login($controller='',$method='') {
$this->load->library('form_validation');
$this->load->model('workout_model');
$this->form_validation->set_rules('ex_password','Koden','trim|required|min_length[4]|max_length[4]|callback_pw_check');
if($this->form_validation->run() == FALSE) {
$this->index();
} else {
if($query = $this->workout_model->validate()) {
$data = array(
'is_logged_in' => true,
'user_id' => $query->id,
'current_exercise' => '1'
);
$this->session->set_userdata($data);
if($controller=='' || $method=='') {
redirect("workout");
} else {
redirect($controller."/".$method);
}
} else {
$this->index();
}
}
}
Two things seem to be necessary for the URL to be correctly updated: use redirect(...) instead of method calls AND disable jQuery Mobile ajax call. Two ways of doing that: add and attribute to the link that initially points to your method,
<a href='.../validate_login/...' data-ajax='false'>...</a>
or, disable ajax calls globally by editing the settings (not tested).
There are two ways to handle this and it has nothing to do with AJAX it's the way CI does things. The quickest and easiest way is to change
$this->index();
to
redirect(index);
The way you're doing it you're not actually redirecting, you're calling the index function on the current URL which is validate_login. The problem with doing it this way is if the login fails it will still remain on the validate_login URL for the next try.
The best way to handle it is to have the actual validate_login function called from your index function in the controller rather than the form itself. So send the form back to index, have the index controller check for the form data and if true call validate_login(). That way you're never actually leaving the index page, it just handles whether or not the login form has been submitted. Solving the URL issue. I actually do this with all my pages that submit forms for any kind of validation.
when you submit via HTML form, such as login register .then you have also some kind of dashboard redirection, you need to update your form tag like this.this occurs when I'm using Codeigniter and jquery mobile use data-ajax="false"
<form id="login-box" method="post" action="<?php echo base_url('index.php/auth/login_user'); ?> " data-ajax="false">

Update page after successful insertion into MySQL table

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.

how to show a pop-up message(like this site) on submit form

i use of php and jquery in my application
i want when users submit success a form in page1 , forward form page1 to page2 and show a pop-up message(like this site) "success" and when they do not submit success , dont forward and just show pop-up message "error"
how i can implement this process?
thanks?
In your form, you can add some javascript into your form tag like so...
<form action="page2.php" onsubmit="if (CONDITION) {alert('Success'); return true;} else { alert('Error'); return false;}">
<input type="submit" value="Submit">
</form>
You can just a call a function ("return checkCondition();") in the onsubmit part and write the function in a separate Javascript file.
If the Javascript in the onsubmit part returns true, then it will go to the page specified in the action. If it returns false, then the form validation fails and it will stay where it is.
You would use something like this:
<?
if($form_success) { //
header("location: formpage2.php?success=1");
}
else {
header("location: formpage1.php?error=1");
}
?>
If you wanted to pass form data from page1 to page2 on success, use either or URL query string or store whatever's in $_POST in $_SESSION.
For the popup message, I would check for a success value in the query string of formpage2 and from there use javascripts alert to alert the user of their success.
I would not rely on Javascript itself in the first "return CheckCondition() in onsubmit" (by Muddybruin), but I would use it! I would not rely on it because the visitor CAN turn of Javascript and easily bypass the functionality.
I would also use the "header-redirection-answer" (by Levi Hackwith), but I would modify it to:
<?php
//checkform.php
if($form_success) {
//Include template or code here when form is successful
}
else {
//Include template or code here when form is unsuccessful
}
?>
If you absoutely must go to a specific file when form is successful, then I would include it instead of redirecting it. This is because redirections can cause unnessary issues regarding to links indexing in searchengines and it would be a lot slower than to just include directly into the checkform.php. Also keep in mind that header redirects must be sent BEFORE any other output is sent from the script.

Categories