php - Codeigniter and jquery Ajax method with Sever side validation -
i using codeigniter jquery ajax call, want is:
show error message codeigniter own form_validation errors.
i using jquery $.ajax
method , getting form values clicking on sumbit
button, handled in formhander.js
file.
i given if($this->form_validation->run() == false)
in condition, when submit form jquery ajax method.
my controller file: ajaxcontroller.php 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 form submission using jquery ajax'; } else { $response['code'] = 500; $response['message'] = 'you must fill name field'; } echo json_encode($response); } } }
my view file: ajax_view.php follow:
<html> <head> <title>this 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
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 when click on submit button whole view file, want show codeigniter form_validation error messages when submit form using jquery ajax method.
let me know if not doing correctly or if not possible.
it possible alright, believe jquery serialize()
method missing in ajax call, meant form processing , got quite few errors before when sent ajax form requests. instead of
var fname = $("#fname").val(); data: data, // ajax call
replace with:
var formdata = $("#myform").serialize(); data: formdata, // ajax call
i'm quite sure it'll trick.
Comments
Post a Comment