I am using Codeigniter with jquery ajax call, What I want is:
to show the error message from Codeigniter own form_validation errors.
I am using jquery $.ajax
method and getting the form values by clicking on sumbit
button, which is handled in formhander.js
file.
I am always given if($this->form_validation->run() == FALSE)
in this condition, when I submit the form by jquery ajax method.
My Controller file: ajaxcontroller.php is as follow:
class AjaxController extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('form_validation');
$this->load->helper('url');
}
public function index() {
$this->form_validation->set_rules('FName', 'First Name', 'required|min_length[1]|max_length[50]');
$response = array('Code' => 500, 'Message' => NULL);
if ($this->form_validation->run() == FALSE) {
$this->load->view('ajax_form');
} else {
$FirstName = $this->input->post('FName');
if ($FirstName != '') {
$response['Code'] = 200;
$response['Message'] = 'Thank you, ' . $FirstName .'For your form submission using jquery ajax';
} else {
$response['Code'] = 500;
$response['Message'] = 'You must fill your NAME field';
}
echo json_encode($response);
}
}
}
My View file: ajax_view.php is as follow:
<html>
<head>
<title>This is testing of jQuery Ajax</title>
<script src="<?php echo base_url('assets/testjs/jquery.js'); ?>"></script>
<script src="<?php echo base_url('assets/testjs/formhandler.js');?>"></script>
<style>
div.invalid {
color: red;
font-size: 12px;
}
</style>
</head>
<body>
<?php echo validation_errors(); ?>
<form method="post" id="MyForm" name="MyForm">
First Name:<input type="text" id="FName" name="FName" /><br>
<input type="submit" id="submit" name="submit" value="Submit" />
</form>
</body>
</html>
My jquery ajax file: formhander.js
is as follow:
$(document).ready(function(){
function handleform() {
$("#submit").live('click',function(){
var fName = $("#FName").val();
var data ='FName='+fName;
console.log(data);
$.ajax({
type: "POST",
url: "http://localhost/ci/index.php/ajaxcontroller/index",
data: data,
dataType: "JSON",
success: function(obj){
if(obj.Code)
$("#output").html(obj.Message);
else
$("#output").html(obj.Message);
}
});
return false;
});
}
});
What I get when I click on the submit button is whole view file, but I want to show the codeigniter form_validation error messages when I submit the form using jquery ajax method.
Let me know if I am not doing it correctly or if it is not possible.
It is possible alright, I believe it is the jQuery serialize()
method that is missing in your ajax call, it is meant for form processing and I got quite a few errors before when I sent ajax form requests. So instead of
var fName = $("#FName").val();
data: data, // ajax call
replace it with:
var formData = $("#myForm").serialize();
data: formData, // ajax call
I'm quite sure it'll do the trick.
Your formhander.js
look strange, as you are defining a function in the $(document).ready()
handler, without calling it.
In consequense the #submit.click
handler is not attached to the button and nothing is intercepting the click.
You should correct you javascript ( I would recommend removing the function handleform()
definition )
You cannot submit directly to the CodeIgniter controller, as CodeIgniter is generating the form tag for you in the view and perhaps also including some extra hidden input.
Include the javascript from your view, then your controller should behave as desired, but you my also want to touch the data posted to have a normal controller behavior if the user disable javascript.
Corrected formhander.js
$(document).ready(function(){
/// attaching event handler to the form submit event
$("form#myForm").submit(function(ev){
ev.preventDefault();
var url=this.action;
$.post( // use of the shorhand function
url,
$(this).serialize(),
function(obj) {
console.log(obj) // you should check this one
if(obj.code == 200 ) {
...
}else{
...
}
},
"json"
);
return false;
});
});
I have made several modifications on your program:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class AjaxController extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper('url');
}
public function index(){
$this->load->view('ajax_form');
}
function clicked(){
$FirstName = $this->input->post('FName');
if ($FirstName != '') {
$response['Code'] = 200;
$response['Message'] = 'Thank you, ' . $FirstName .'For your form submission using jquery ajax';
} else {
$response['Code'] = 500;
$response['Message'] = 'You must fill your NAME field';
}
echo json_encode($response);
}
}
In your controller, I separated the loading of your ajax_form view to your ajax function, note: ajax and code igniter form validations will not work together because CI form validation needs to refresh the page in order to display the result of the validation.
<script>
$(document).ready(function(){
//function handleform() { //removed the function handleform() because you will no longer need it, and you are not calling it in the first place.
$("#submit").on('click',function(){ //replace live with on.
var fName = $("#FName").val();
var data ='FName='+fName;
console.log(data);
$.ajax({
type: "POST",
url: "http://localhost/ci/index.php/AjaxController/clicked",
data: data,
dataType: "json",
success: function(obj){
//if(obj.Code == 200) //Note: if Statements only evaluates if it is true or false. you did not compare obj.Code to anything, and obj.Code is not true nor false
//{
alert(obj.Message); //Note: I have removed your if condition because you will no longer need it. The message you sent from the server to client is already evaluated, there is no need to re-evaluate it in the client.
//$("#output").html(obj.Message); output element is not found here, so i just alerted your message
//}
//else
//{
//alert(obj.Message);
//$("#output").html(obj.Message);
//}
}
});
//return false; you don't need to return anything here.
});
//}
});
</script>
<html>
<head>
<title>This is testing of jQuery Ajax</title>
<style>
div.invalid {
color: red;
font-size: 12px;
}
</style>
</head>
<body>
First Name:<input type="text" id="FName" name="FName" /><br>
<input type="submit" id="submit" name="submit" value="Submit" />
</body>
As of jQuery 1.7, the .live() method is deprecated, so you should use on
. Notice That I removed the <form>
tag, because when you click an input button with type submit
it will trigger a page refresh..