I want to validate my form which is in bootstrap modal. But all time validation_errors() returning empty string. I am using Codeigniter 3 and HMVC.
here is my ajax code
$('#add_unload').on('click', function (e) {
e.preventDefault();
var carrier_type = $.trim($('#carrier').val());
var truck_plateno = $.trim($('#truck_plateno').val());
$.ajax({
url: site_url + 'pre_unload/add',
type: 'get',
dataType: 'json',
data: {
carrier_type : carrier_type,
truck_plateno:truck_plateno
}
}).done(function (response) {
console.log(response);
});
});
and here is my controller's add method
public function add() {
if (!$this->input->is_ajax_request()) {
die('wrong');
}
$carrier_type = $this->input->get('carrier_type', TRUE);
$this->form_validation->set_rules('truck_plateno', 'Truck Plate', 'required');
if ($carrier_type == 'O') {
$this->form_validation->set_rules('another_filed', 'XXXX', 'required');
} else {
$this->form_validation->set_rules('another_filed', 'XXXX', 'required');
}
if ($this->form_validation->run() === FALSE) {
$this->load->helper('form');
echo json_encode(array('err' => validation_errors()));
return;
}
}
var_dump($this->form_validation->run());return; always return false and validation_errors() return empty string. I have tried this too $this->form_validation->run($this) still no luck. My_form_validation.php also ok in library
** I have loaded form_validation library in construct
Any IDEA?
Related
I am trying to make ajax form validation work in codeigniter.
Form and ajax are both in views/products/addproducts,
<script type="text/javascript">
$(document).ready(function(){
$("#submitProducts").click(function(e){
e.preventDefault();
var dataString = $("#add-products-bulk-form").serialize();
var url="products/addproducts";
$.ajax({
type:"post",
url:"<?php echo base_url() ?>"+url,
dataType: 'json',
data:dataString,
success:function (res) {
res=$.parseJSON(res);
if($.isEmptyObject(res.error)){
alert(res.success);
}else{
console.log("hasn't run form yet");
}
},
})
})
});
</script>
here is my Products controller:
public function addproducts()
{
$data['title'] = "Add Products";
$this->load->view('templates/header', $data);
$this->load->view('products/addproducts');
$this->load->view('templates/footer');
//form rules
//$this->form_validation->set_rules('name[]', 'Product Name', 'required');
$this->form_validation->set_rules('partnumber[]', 'Part number', 'required|is_unique[items.itemSKU]');
//$this->form_validation->set_rules('msrp[]', 'MSRP', 'required');
if ($this->form_validation->run() === FALSE)
{
echo "did not pass validation";
$errors = validation_errors();
echo json_encode(['error'=>$errors]);
}
else
{
echo "did pass validation";
$this->product_model->add_products();
echo json_encode(['success'=>'Record added successfully.']);
}
}
I don't get any response when I click submit button if I keep the code above way. But if I get rid of line dataType:'json', I will get error
VM1679:1 Uncaught SyntaxError: Unexpected token d in JSON at position 0
at Function.parse [as parseJSON] (<anonymous>)
at Object.success (addproducts:140)
at i (jquery-3.1.1.min.js:2)
at Object.fireWith [as resolveWith] (jquery-3.1.1.min.js:2)
at A (jquery-3.1.1.min.js:4)
at XMLHttpRequest.<anonymous> (jquery-3.1.1.min.js:4)
If I get rid of both dataType:'json' and res=$.parseJSON(res), when I enter a duplicated product and click submit, and console.log(res), I get the following in the console, It did return the res and the source code of the whole page addproducts.
did not pass validation{"error":"<p>The Part number field must contain a unique value.<\/p>\n"}<!DOCTYPE html>
<html lang="en">
<head>
I did not paste the whole source code here. and res.success will alert undefined.
I have been stuck for days, please help. I will provide more details if needed.
Thanks!
To clean up my earlier comment...
public function addproducts()
{
//form rules
//$this->form_validation->set_rules('name[]', 'Product Name', 'required');
$this->form_validation->set_rules('partnumber[]', 'Part number', 'required|is_unique[items.itemSKU]');
//$this->form_validation->set_rules('msrp[]', 'MSRP', 'required');
header('Content-Type: application/json');
if ($this->form_validation->run() === FALSE)
{
$this->output->set_status_header(400);
$errors = validation_errors();
echo json_encode(['error'=>$errors]);
}
else
{
$this->output->set_status_header(200);
$this->product_model->add_products();
echo json_encode(['success'=>'Record added successfully.']);
}
}
Now you can use the success callback to listen for a successful response and the error callback to listen for an error response...
<script type="text/javascript">
$(document).ready(function(){
$("#submitProducts").click(function(e){
e.preventDefault();
var dataString = $("#add-products-bulk-form").serialize();
var url="products/addproducts";
$.ajax({
type:"post",
url:"<?php echo base_url() ?>"+url,
dataType: 'json',
data:dataString,
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR.responseJSON.error);
},
success: function (data, textStatus, jqXHR) {
alert(jqXHR.responseJSON.success);
}
});
});
});
</script>
I realized that I make ajax call with the same controller function, I divided the addproducts function into two functions as follow,and use ajax to call ajax_add_products function. it works now.
public function addproducts()
{
$data['title'] = "Add Products";
$this->load->view('templates/header', $data);
$this->load->view('products/addproducts');
$this->load->view('templates/footer');
}
public function ajax_add_products(){
//form rules
//$this->form_validation->set_rules('name[]', 'Product Name', 'required');
$this->form_validation->set_rules('partnumber[]', 'Part number', 'required|is_unique[items.itemSKU]');
//$this->form_validation->set_rules('msrp[]', 'MSRP', 'required');
if ($this->form_validation->run() === FALSE)
{
$errors = validation_errors();
echo json_encode(['error'=>$errors]);
}
else
{
$this->product_model->add_products();
echo json_encode(['success'=>'Record added successfully.']);
}
}
Okay, so before I ask my question I will explain the flow of things. Form submits data to add() method (localhost/share/add) in the ShareController, from there it is shipped over to the ShareModel method createShare() where the magic is supposed to happen.
My AJAX code:
var formData = $(form).serialize();
var form = $("#add-share");
$(form).submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData,
dataType : "json",
success : function(data) {
if(data == 1) {
alert("Woohoo!");
} else {
alert("Womp!");
}
console.log(data);
}
})
});
ShareController add() method:
public function add() {
ShareModel::createShare(Request::post('share_title'));
Redirect::to('share');
}
ShareModel createShare() method:
public static function createShare($share_title) {
if(strlen($share_title) > 55) {
Session::add('feedback_negative', Text::get('FEEDBACK_SHARE_TITLE_LONG'));
return false;
}
if(strlen($share_title) < 5 || empty($share_title)) {
Session::add('feedback_negative', Text::get('FEEDBACK_SHARE_TITLE_SHORT'));
return false;
}
$data[] = 0;
echo json_encode($data);
}
The issue:
Ajax is returning everything fine "Womp!" when I have the backend PHP validation commented out, however when I have it implemented the AJAX does not work, and the backend validation does not take over. Anyone have an ideas what's going on here?
Controller code below as show unable to login.
none of the error getting what is the problem i cannot understand how to call through ajax
public function loginn()
{
$email=$this->input->post('email');
$password=$this->input->post('password');
//$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email or number', 'required|min_length[10]|max_length[30]');
$this->form_validation->set_rules('password', 'password', 'trim|required|min_length[4]|max_length[40]');
if ($this->form_validation->run() && $this->Login_model->login($email, $password)) {
$this->welcome();
}
else {
$this->form_validation->set_message('check_database', 'Invalid username or password');
$this->index();
}
}
Below code as shown View page send the post values through ajax.script as below.how to pass the post values to controller using ajax.
<script type="text/javascript">
$(document).ready(function(){
$("#fpassf").click(function(){
//e.preventDefault();
var email = $("#email").val();
var password= $("#password").val();
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>"+"Index.php/Login_cntrl/loginn",
data: {email:email,password:password},
success:function(data)
{
alert('Successfully login');
},
error:function()
{
alert('fail');
}
});
});
});
the image shown in below
enter image description here
on click on signin image shown in below
enter image description here
It seems that you are using Codeigniter Framework. And Hence I have a doubt with your Ajax URL Path.
You have given
url: "<?php echo base_url() ?>"+"Index.php/Login_cntrl/loginn",
But In codeigniter it should be like
url: "<?php echo base_url() ?>"+"/Login_cntrl/loginn",
OR
url: "<?php echo base_url('Login_cntrl/loginn') ?>",
It can also possible that you are calling this ajax from a script file. Which is not a php file. so the base_url() function will not work there. In that case you have to save base_url into a input variable in a hidden format. and then should be fetch in your ajax code.
<input type="hidden" name="myurl" value="<?php echo base_url();">
and then ajax one
var myurl = $("#myurl").val();
You have to separate your basic login action and ajax login action, because both send different response.
PHP Controller:
public function ajax_login()
{
$email = $this->input->post('email');
$password = $this->input->post('password');
$this->form_validation->set_rules('email', 'Email or number', 'required|min_length[10]|max_length[30]');
$this->form_validation->set_rules('password', 'password', 'trim|required|min_length[4]|max_length[40]');
if ($this->form_validation->run() && $this->Login_model->login($email, $password)) {
return $this
->output
->set_status_header(200)
// here you tell to the ajax that the login is successful
->set_output(json_decode(array('status' => 'success', 'message' => 'PUT_YOUR_SUCCESS_MESSAGE_HERE')))
;
} else {
return $this
->output
->set_status_header(200)
// here you tell to the ajax that the login is failed
->set_output(json_decode(array('status' => 'error', 'message' => 'PUT_YOUR_ERROR_MESSAGE_HERE')))
;
}
}
Javascript:
<script type="text/javascript">
$(document).ready(function(){
$("#fpassf").click(function(){
var email = $("#email").val();
var password = $("#password").val();
$.ajax({
type: "POST",
url: "<?php echo base_url('Login_cntrl/ajax_login') ?>",
data: {email:email, password:password},
success: function(data) {
data = JSON.parse(data);
// success in ajax does not mean successfully login, so check again
if (data.status == 'success') {
alert(data.message]); // login success message defined in action
} else {
alert(data.message); // login failed message defined in action
}
},
error: function() {
// error in ajax means HTTP error, not login error
alert('Request failed!');
}
});
});
});
</script>
I need help. I am getting problem in returning value from Codeigniter. Whenever, I use exit; after echo it work fine but whenever i try return true it's dosen't work.
Same as i have comment code in PHP code. if i use exit after echo it works but if i don't do that it returns nothing
Ajax Request
$('#social-form').on('submit', function(e){
e.preventDefault();
var str = $( "#social-form" ).serialize();
if (str === '') {
swal("Please Fill All Fields");
} else {
$.ajax({
type: "POST",
url: baseUrl + "/admin/social/",
data: str
})
.done(function (data) {
console.log(data);
swal("Information", data, "info");
})
.error(function () {
swal("Oops", "We couldn't connect to the server!", "error");
});
}
});
Codeigniter-3
public function social(){
$name = $this->input->post('name');
$profile = $this->input->post('profile');
$this->form_validation->set_rules('name', 'name', 'required|trim');
$this->form_validation->set_rules('profile', 'profile', 'required|trim');
if ($this->input->post() && $this->form_validation->run() != FALSE) {
$this->load->model('Social_model','social');
$this->social->update($name,$profile);
echo 1;
//exit;
//return true;
}
else
{
echo 0;
//exit;
//return false;
}
}
CodeIgniter has a layout, so after outputting a response there could be views that are outputted after your response, such as a footer or a debug bar.
Try using your console to see the status code of the response. Also note that it isn't bad practice in CodeIgniter to exit after AJAX calls, so perhaps you should just write a AJAX response helper which does all that for you (like setting the header and adding the exit).
You probably need to be more specific about what you echo. This is one of several possible solutions.
controller
public function social(){
$name = $this->input->post('name');
$profile = $this->input->post('profile');
$this->form_validation->set_rules('name', 'name', 'required|trim');
$this->form_validation->set_rules('profile', 'profile', 'required|trim');
if ($name && $this->form_validation->run() != FALSE) {
$this->load->model('Social_model','social');
$this->social->update($name,$profile);
$out = json_encode(array('result' => 'success'));
}
else
{
$out = json_encode(array('result' => 'failed'));
}
echo $out;
}
javascript
$('#social-form').on('submit', function (e) {
e.preventDefault();
var str = $("#social-form").serialize();
if (str === '') {
swal("Please Fill All Fields");
} else {
$.ajax({
type: "POST",
url: baseUrl + "/admin/social/",
data: str,
dataType: 'json'
})
.done(function (data) {
console.log(data);
if (data.result === 'success') {
swal("Information", "Success", "info");
} else {
swal("Information", "Failed", "info");
}
})
.error(function () {
swal("Oops", "We couldn't connect to the server!", "error");
});
}
});
My controller is
public function init()
{
/* Initialize action controller here */
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('get-ajax-content', 'html')
->initContext();
}
public function indexAction()
{
// action body
$form = new Zend_Form_Element_Select('menu');
$parent_array=range('1','9');
$form->addMultiOptions(array($parent_array));
$this->view->form = $form;
}
for this form element, i am calling the ajax function,
<script type="text/javascript">
$(document).ready(function(){
$("#menu").change(function(){
$.ajax({
type: "POST",
url: "get-data",
data: "val="+$(this).val(),
success: function(result){
$("#div_sortorder").html(result);
},
error: function(){
//console.log('error');
},
complete: function(){
//console.log('complete');
}
});
});
</script>
and the get-data action is following
public function getDataAction()
{
// action body
$this->view->message = 'This is an ajax message!';
$params = array( 'host' =>'localhost',
'username' =>'root',
'password' =>'',
'dbname' =>'cms'
);
$DB = new Zend_Db_Adapter_Pdo_Mysql($params);
$section_id=$this->getRequest()->getPost('val');
$menu_order='SELECT * FROM `cms_content_mst` WHERE section_id='.$section_id;
$menu_order=$DB->fetchAll($menu_order);
$newContent='<select id="sortorder" name="sortorder">';
if(!empty($section_id) || $section_id != 0){
if (empty($menu_order)) {
$newContent.='<option value="1" selected="selected">1</option>';
}
else
{
for ($i=1; $i <= count($menu_order) ; $i++) {
$newContent.='<option value="'.$i.'"';
if($i==count($menu_order))
{ $newContent.=' selected'; }
$newContent.='>'.$i.'</option>';
}
}
}
$newContent.='</select>';
$this->view->new = $newContent;
}
i have fully worked jquery . i have .get function but on calling .ajax its is not working
i am newbee to zend plz, help
Please! Check in console if you are able to load page.
$.ajax({
type: "POST",
url: "get-data",
data: "val="+$(this).val(),
success: function(result){
$("#div_sortorder").html(result);
}
I think you have given wrong url.