I am new to PHP Codeigniter framework. I am designing a page in which I am using a link. On clicking the link it is calling a jquery function, which submits form through jquery. I have used codeigniter form validation methods for server side validation and for the timebeing I have disabled the client side validation.
The problem is that in this process when the form is submitted through jquery, the codeigniter form validation method is not working.
But if I am using a submit button to submit the form then the codeigniter form validation method works perfectly.
Please advise me what to do if I need to submit the form through jquery and use the codeigniter form validation method.
Please find the code below:
Login Form:
<?php echo validation_errors(); ?>
<form name="login-form" id="login-form" method="post" action="<?php echo base_url();?>index.php/login/login_form" >
<H2>Login</H2>
<div id="login-box-name">
Email:
</div>
<div id="login-box-field">
<input name="user-name" id="user-name" class="form-login" title="Please Enter Correct User Name" value="" size="30" maxlength="2048" />
</div>
<div id="login-box-name">
Password:
</div>
<div id="login-box-field">
<input name="password" id="password" type="password" class="form-login" title="Please Enter Correct Password" value="" size="30" maxlength="2048" />
</div>
<br />
<span class="login-box-options">
<input type="checkbox" name="1" value="1" title="Want this computer to remember you!!"> Remember Me Forgot password?
</span>
<br />
<br />
<a href="" id="login-submit">
<img src="<?php echo base_url();?>assets/images/login-btn.png" width="110" height="40" style="margin-left:90px;" />
</a>
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
jquery function to submit the form on clicking the "link":
$("#login-submit").click(function()
{
$('#login-form').submit();
return false;
});
Controller function:
public function login_form()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$data['title'] = 'Log In';
$data['errorMessage'] = '';
$this->form_validation->set_rules('user-name', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('login', $data);
$this->load->view('templates/footer');
}
else
{
$this->load->view('templates/header', $data);
$this->load->view('templates/menu');
$this->load->view('index', $data);
$this->load->view('templates/footer');
}
}
Here if I click on the "Submit button of the form, then the codeigniter validation works for user-name and password fields. But if I click the link with id="login-submit", then it calls the jquery function and the form get submitted. But the codeigniter validation does not work for user-name and password fields this time.
I need to submit the form through the link and the codeigniter validation function should work for this.
Thanks in Advance.....
Use .preventDefault() instead of just returning false on the anchor click event.
This has happened to me before and it seems to me that there is a conflict somewhere using .submit() inside a click event and returning false to stop the anchor's default behavior.
The code above is working fine. Actually I made a silly mistake in my code.
I used following code for jQuery and it is working now.
$("#login-submit").click(function(e) {
e.preventDefault();
$('#login-form').submit();
});
Thanks
it happens because it calls the function all the time when clicking on the button. you need to stop that.
$("#login-submit").click(function(e){
e.preventDefault();
$('#login-form').submit();
});
Related
I have a input field
<?php
echo form_open('moneyexchange/borrow_first_page'); ?>
<input id ="Amount" type="text" placeholder="Amount in €" name="writtenamount">
<a type="submit" href="<?php echo base_url();? >index.php/moneyexchange/invest_first_page">invest</a>
</form>
And in codeigniter moneyexchange controller I have a function here
public function invest_first_page(){
$this->load->helper('form');
$this->load->library('form_validation');
$this->load->view('header');
$userProvidedAmount = $this->input->post("writtenamount");
$data = array(
'userProvidedAmount' => $userProvidedAmount
);
$this->load->view("invest_firstpage", $data);
$this->load->view('footer');
}
But for some reason I cannot get the value from the input field in the view file to the controller, please help.
it shows that my $userPRovidedAmount is a (bool)false value. But I need to get numbers from the input variable
You have a link where your submit button should be. A link wont submit the form (unless there is some unseen javascript) - it will just make a regular GET request to the page (hence why POST is empty in your controller)
Change the action of your form and make the submit button a form element:
<?php echo form_open('moneyexchange/invest_first_page'); ?>
<input id ="Amount" type="text" placeholder="Amount in €" name="writtenamount"/>
<input type="submit" value="invest"/>
<?php echo form_close();?>
once again I'm lost. I'm gonna start ahead with the issue, because I am not even sure what I really want.
Example:
I have an article view. The URL is: http://index.php/news/article/3
This actually runs the article($id) function in my news controller and gives it the 3 as an argument. The function then fetches the article information and displays it in the view.
On the article page, the user can also log in. Logging in is triggered on pressing
submit button inside my form form_open('core/login')...button...</form> In the function I log the user in and refresh the current view with some elements changed according to the user being logged. The problem is that the URL is now http://index.php/core/login. Obviously I would like it to be the original URL.
Is there any, possibly simple, solution to achieve this? Thank you all for reading and in advance for your replies.
Difficult without more code but let me give you my theory / take on this:
Default controller:
User is not logged in - show default header, content, footer
User presses login, form is shown
User is authenticated - yes (continue) no (go back to form)
User is redirect('home')'d
Your default controller/home controller checks if auth'd: if authorised then show logged in header, content and logged in footer
or simply pass 'loggedIN' as a $data['loggedIN'] variable to the view - but this breaks the ideology of MVC framework.
More info from you and I can be more specific, or we can talk on IRC.
Adding this code from a controller i'm working on right this minute - I use ion_auth library (you should look it up, it's excellent).
This is my default controller - and as you can see some simple logic loads the different views/states.
public function index(){
if ($this->data['auth_login'] ) {
/*is already signed in so just present the lobby?*/
$data['page_title'] = "HN Lobby";
$data['menuItems'] = nav_anchor_helper_authd();
$data['myUserID'] = $this->ion_auth->get_user_id();
$data['lobby_players'] = $this->lobby_model->get_players();
$this->load->view('template/public/header',$data);
$this->load->view('player_pages/nav_2',$data);
$this->load->view('player_pages/lobby',$data);
$this->load->view('template/scripts/main',$data);/*scraper and other scripts*/
$this->load->view('template/public/footer',$data);
} else {
/*request login*/
$data['page_title'] = "PLAY HN";
$data['menuItems'] = nav_anchor_helper();
$data['auth_rtnurl'] = current_url();
$data['auth_conturl'] = current_url(); /*for now just come back to same page where lobby should load - perhaps in future a semi gooey login? e.g where was user going - this could be the continue url in this var right here << */
$data['message_body'] = $this->session->flashdata('message');
$this->load->view('template/public/header',$data);
$this->load->view('template/public/nav_1',$data);
$this->load->view('public_pages/play',$data);
$this->load->view('template/public/footer',$data);
}
}
Here is how I handle the return URL in my login function:
Login/auth controller: (using ion_auth)
function login()
{
$this->data['title'] = "Login";
//validate form input
$this->form_validation->set_rules('identity', 'Identity', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == true)
{
if ($this->ion_auth->login($this->input->post('identity'), $this->input->post('password'), $remember))
{
//if the login is successful
//redirect them back to the home page
$this->session->set_flashdata('message', $this->ion_auth->messages());
$rtnurl = $this->input->post('auth_conturl');
if(!$rtnurl || $rtnurl == ""){
$rtnurl = '/';
}
redirect($rtnurl, 'refresh');
}
This is only an extract/segment of the login function - but as you can see i utilise the function 'redirect' from code igniter to push the user back to the return URL posted with the login form (which was set in the view/previous controller using the current_url() function.
Finally my default view file with login form to show you how i am passing the return url:
<div>
<h4>Login</h4>
<div id="infoMessage" class="errortext"><?php echo $message_body;?></div>
<?php echo form_open('auth/login', array('class' => 'form col')); ?>
<p>
<label for="identity">Email:</label> <input type="text" name="identity" value="" id="identity"> </p>
<p>
<label for="password">Password:</label> <input type="password" name="password" value="" id="password"> </p>
<p>
<label for="remember">Remember Me:</label> <input type="checkbox" name="remember" value="1" id="remember"> </p>
<p><input type="submit" name="submit" value="Login »"></p>
<p>
Forgot password ?
</p>
<input type="hidden" name="auth_rtnurl" value="<?php echo $auth_rtnurl; ?>"/>
<input type="hidden" name="auth_conturl" value="<?php echo $auth_conturl; ?>"/>
<?php echo form_close();?>
</div>
To use the current dynamic url as form action, just use -
<?= form_open(current_url()); ?>
I've checked and re-checked my code, referencing the CI docs and other posts throughout the web, but I am unsuccessful at implementing the set_value() method for re-populating form fields after failed validation.
Perhaps I am missing something very fundamental to the CI framework (I'm rather new to it), but your insight would be much appreciated.
I have the following in my controller method:
public function form_step2(){
//Form Setup
$this->load->helper('form');
$this->load->helper('url');
$this->load->library('form_validation');
$data['title'] = $this->base_title;
$data['base_url'] = base_url();
//Validation Settings - must be set per step
$this->form_validation->set_rules('request_type', 'Request Type', 'required');
*...more of the same set_rules()*
if ($this->form_validation->run() === FALSE) {
### Validation failed or New Form
// Get form element data
$data['request_types'] = $this->my_model->get_form_data('request_type');
*...more of the same get_form_data() calls for loading form elements*
//Generate Page from View Templates
$this->load->view('templates/header', $data);
$this->load->view('templates/form_step2', $data);
$this->load->view('templates/footer');
} else {
### Save to database
$this->my_model->set_data($data);
redirect('my_model/success','refresh');
}
}
And in my view, a snippet of the code that is not re-populating:
<?php echo form_open('my_model/form_step2', array('class'=>'form-inline')); ?>
<label for="fname">First Name</label>
<input type="text" id="fname" name="fname" value="<?php echo set_value('fname'); ?>" />
<input type="submit" name="submit" value="Submit" />
I can't figure this one out, so thanks in advance for your help.
if you want to use set_data() you need to also use set_rules for that POST/GET field.
Since you've commented out all your set_rules I can not confirm that this is the issue but most likely it is.
please check if you have this line in your code
$this->form_validation->set_rules('fname', 'First name', 'trim|required');
So if you want to re-populate field with name="fname" you need to have set_rules() // as line above for it otherwise it won't process therefore set_value('fname') is empty.
you surely have found a solution but, for people like me which were spending too many time for this trouble.
I found a solution:
so instead to code that
<input type="text" id="fname" name="fname" value="<?php echo set_value('fname'); ?>" />
Try this, it run very well:
<?php $data = array('id' =>fnam, 'name'=> 'fname','value'=> set_value('fname'), 'size =>'50');
echo form_input($data).'<br />'; ?>
Try this way. It will get both validation errors and set value
In View
<?php echo flash_message();
if($this->session->userdata('postinput') !=""){
$value = $this->session->userdata('postinput');
$this->session->unset_userdata('postinput');
}else
$value = "";
?>
<form action="<?php echo site_url('carlisting/carlist');?>" method="post" id="your_reg_form">
<div class="reg-search">
<input placeholder="YOUR REG" name="input" type="text" value="<?php echo $value; ?>">
</div>
In Controller
$this->form_validation->set_rules('input', 'Registration', 'required|min_length[2]|max_length[7]');
if ($this->form_validation->run() == false){
$this->session->set_flashdata( 'message', array('content' => validation_errors(), 'type' => 'error_message_small' ));
$this->session->set_userdata('postinput',$this->input->post('input'));
redirect('home');
}
Permits you to set the value of an input form or textarea. You must supply the field name via the first parameter of the function. The second (optional) parameter allows you to set a default value for the form. Example:
<input type="text" name="quantity" value="<?php echo set_value('quantity', '0'); ?>" size="50" />
The above form will show "0" when loaded for the first time.
What i would like to do, is instead of loading up a separate page to input data into a database, i would like to pop open a dialog, and upon submission, it would add data to the database and refresh the page.
For example: I'm on the index page and want to add another entry to a datagrid. I would click a button that adds a new entry. A dialog pops up, i add information into it, and hit submit. It would then refresh and remain on the index page.
This is what i currently have, but it doesn't do anything right now.
Index page:
<div id="createEntry">
<button>Create new item</button>
</div>
$("button")
.button().click(function(){
$.post('<?php echo base_url(); ?>test/create', function(response){
$('#dialog').html(response);
});
});
Create page
<div id="dialog" title="Create new test case">
<?php echo form_open(base_url() . 'test/create') ?>
<label for="title">Title</label><br />
<input type="text" name="title" /><br />
<label for="something">Something</label><br />
<textarea name="something"></textarea><br />
<input type="submit" name="submit" value="Create" />
</div>
<script>
$("#dialog").dialog();
</script>
Controller
public function create()
{
//...
//some code here for validation
//
if ($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header', $data);
$var = $this->load->view('test/create', '', TRUE);
$this->load->view('templates/footer');
}
else
{
//adds to db
$this->test_model->set();
}
}
I feel like i'm close. There's just something i'm missing
Any help is appreciated.
Simple answer. I needed a <div id="dialog"> on the index page.
I have a form which I want to submit, so when I click on submit it goes to the selectorpage.php and finds the selected function type e.g. login in this, which further calls the controller to execute the function. Issue I have is that there is a function called validateForm() in js, as soon as I click the submit button, it goes to the selectorPage.php. I wanted to stop the form submission, perform validation through js and then submit the form from there, I used onsubmit = return false; in form tag but it just blocks the form of doing anything further. And I also don't know how to redirect the form to the selectorPage if it somehow works in js. So anybody would like to give me an idea how to submit form from js and then redirect that page to selectorPage.php. Thanks
<form method="post" action="selector.php?type=login" id="login" id="loginForm">
<div class="row">
<div class="offset1 span1">
<div class="lbel">
<label class="control-label" for "loginName">
Username/Email
</label>
</div>
<div class="lbl_inpuCnt">
<input type="text" class="input-xlarge" id="loginName"
name="loginName" maxlength="50"/>
</div>
<div id="usernameError"> </div>
<div class="lbel">
<label class="control-label" for="loginPassword">
Password
</label>
</div>
<div class="controls">
<input type="password" class="input-xlarge"
id="loginPassword" name="loginPassword"
maxlength="50"/>
</div>
<div id="passwordError"> </div><br/>
</div>
</div>
<div style="margin-left: 55px;">
<input class="btn" style="width: 80px;" type="reset"
name="reset" value="Reset"/>
<input class="btn" style="width: 80px;" type="submit"
name="submit" value="Login" onclick="validateForm();"/>
</div>
</form>
this is the javascript according to the code above
function validateForm(){
form = document.forms['loginForm'];
if(document.getElementById('loginName').value == "")
document.getElementById('usernameError').innerHTML = 'Invalid username or email';
else{
document.getElementById('usernameError').innerHTML = " ";
form.submit();
}
} //suppose it for the email validation only for the time being
you could try
<form ... onsubmit="return validateForm();"
in the validateForm() function use
return true / false
depending if errors are found.
Here is the canonical way using inline event handling - see further down how it could be made unobtrusive. Also only have ONE id on the form tag, also NEVER call anything submit in a form it is a reserved word and will block submitting by script (which is what you tried to do)
<form id="loginform" ... onsubmit="return validate(this)">
<div style="margin-left: 55px;">
<input class="btn" style="width: 80px;" type="reset" name="reset" value="Reset" onclick="clearFields()"/>
<input class="btn" style="width: 80px;" type="submit" value="Login" />
</div>
</form>
this is the javascript
function validateForm(form){ // passing form object
document.getElementById('usernameError').innerHTML = ""; // reset
if (form.loginName.value == "") {
document.getElementById('usernameError').innerHTML = "Invalid username";
return false;
}
return true;// allow submission
}
Alternative
<form id="loginform" ..... No event handler here ...>
Script:
window.onload=function() {
document.getElementById("loginform").onsubmit=function() {
document.getElementById('usernameError').innerHTML = ""; // reset
if (this.loginName.value == "") { // notice the "this"
document.getElementById('usernameError').innerHTML = "Invalid username";
return false;
}
return true;// allow submission
}
}
I've had similar issues to this in the past myself.
When you click the 'Login' button of your form, you are triggering two separate events - Calling of the 'validateForm();' javascript function, and submission of the form itself. The problem here, is that submitting the form involves the browser sending an outbound request back to the form target, and to my knowledge, there is no way, using javascript, to kill a request event once it has been triggered.
Using 'onsubmit=return false;', likely, is doing exactly what it is supposed to do - Exiting the current javascript scope (and therefore preventing further javascript associated to that particular event from executing). However, unfortunately, the submission of the form itself, while possible to trigger and control via javascript, is not actually handled by javascript and is not a javascript function itself.
What I've found, in my experiences, to be the best solution, is to use the 'button' type input instead of the 'submit' type input - Both 'submit' and 'button' appear as buttons, but 'button' doesn't actually have any default inherent associated event action (therefore, doesn't actually do anything when you click on it) - What this means, is that, via event handlers (such as 'onclick', as you've done), you are able to entirely control what happens when a user clicks on a 'button'.
You haven't included your 'validateForm();' javascript function here, so I don't know what it contains, but, if it doesn't already do so, I'd include code to submit the form via that javascript function, submitting the form once validation has been successful (or returning some sort of human readable error if validation fails) - That combined with using 'button' instead of 'submit' should solve your problem.
Hope this helps. :)
Edit: Thought of this shortly after making my initial reply. Some browsers will process events handlers such as 'onclick' prior to submitting forms via the submit input type; However, I've found that certain older browsers do not do this currently (thus context of my above post). For newer browsers that honour the results of event handlers processed prior to form submission, it should be possible to prevent the second event (form submission) from occurring at all if validation fails; However, not all browsers honour these results, and I've found that some will continue to submit the form regardless of those results.
well thanks u all, so finally I found the solution by your ideas here is what I have done
rather putting return formvalidate(); function I put it in submit onclick event and it run like charm... thanks
<div style="margin-left: 55px;">
<input class="btn" style="width: 80px;" type="reset" name="reset" value="Reset" onclick="clearFields()"/>
<input class="btn" style="width: 80px;" type="submit" name="submit" value="Login" onclick="return validateForm();"/>
</div>
this is the javascript
function validateForm(){
var form = document.forms['loginForm'];
if(document.getElementById('loginName').value == "")
document.getElementById('usernameError').innerHTML = 'Invalid username or email';
else{
form.submit();
}
return false;
}