Try it. It will work fine.
In the controller, add these two methods
public function CreateStudents() { $this->load->helper('form'); $data['title'] = "Create Students Page"; $data['success'] = ""; $this->load->view('templates/header', $data); $this->load->view('createstudents', $data); $this->load->view('templates/footer', $data); } public function CreateStudentsAjax() { $this->load->helper('form'); $this->load->library('form_validation'); $this->form_validation->set_error_delimiters('', ''); $this->form_validation->set_rules('roll', 'Roll Number', 'required'); $this->form_validation->set_rules('name', 'Name', 'required'); $this->form_validation->set_rules('phone', 'Phone', 'required'); if ($this->form_validation->run()) { $this->welcome_model->InsertStudents(); echo json_encode("Oks"); } else { $data = array( 'roll' => form_error('roll'), 'name' => form_error('name'), 'phone' => form_error('phone') ); echo json_encode($data); } }
In the View Add Form and DIV named " mesage "
<div id="message"> </div> <?php echo form_open('welcome/CreateStudentsAjax'); ?> <label for="roll">Student Roll Number</label> <input type="text" id="txtRoll" value="" name="roll"/> <label for="Name">Students Name</label> <input type="text" id="txtName" value="" name="name"/> <label for="Phone">Phone Number</label> <input type="text" id="txtPhone" value="" name="phone"/> <input type="submit" name="submit" value="Insert New Students" /> <?php echo '</form>'; ?>
Scripts now contain
<script type="text/javascript"> $(document).ready(function(){ $('form').submit(function(){ //alert('ok'); $.ajax({ url:this.action, type:this.method, data:$(this).serialize(), success:function(data){ var obj = $.parseJSON(data); if(obj['roll']!=null) { $('#message').text(""); $('#message').html(obj['roll']); $('#message').append(obj['name']); $('#message').append(obj['phone']); } else { $('#message').text(""); $('#message').html(obj); } }, erro:function(){ alert("Please Try Again"); } }); return false; }); }); </script>
source share