user3840485
user3840485

Reputation: 5075

codeigniter form submission using ajax and display return data in a div

I need to submit form data using ajax and get auto increment id of submitted record and display it on a div

here is my code

controller

<?php
class Form_controller extends CI_controller{

function index(){
    $this->load->view('submit_form');
}
public function insert_into_db(){
$this->load->model('form_model');
$this->form_model->insertQ();  

} }

view

<html>
<body>
    <form method="post" name="myForm1" id="myForm1" enctype="multipart/form-data" >
        Email: <input type="text" name="email" id="email">
        Question: <input type="text" name="qText" id="qText">
        <input id="submitbutton" type="submit">
    </form>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script>   //no need to specify the language
        $(function(){
         $("#submitbutton").click(function(e){  // passing down the event 

           $.ajax({
              url:"<?php echo site_url('form_controller/insert_into_db'); ?>",
              type: 'POST',
              data: $("#myForm1").serialize(),
              success: function(){
                  alert("success");
                  $('#email').val('');
                  $('#qText').val('');
              },
              error: function(){
                  alert("Fail")
              }
          });
          e.preventDefault(); // could also use: return false;
        });
       });
    </script>   
</body>
</html>

model

<?php

 class Form_model extends CI_Model{

function insertQ(){
$email = $this->input->post('email');
$qText = $this->input->post('qText');
$this->db->insert('questions', array('email' =>$email, 'text' => $text));

} }

I have tried several times,but couldn't fix it,I'm new to codeigniter as well ajax

Upvotes: 0

Views: 714

Answers (1)

Hammad
Hammad

Reputation: 2137

You are doing it wrong. You are getting post variables in model function rather than in controller function.

After that, your controller function will be like this:

<?php
class Form_controller extends CI_controller{

function index(){
    $this->load->view('submit_form');
}
public function insert_into_db(){
$this->load->model('form_model');
$this->form_model->insertQ($this->input->post('email'),$this->input->post('qText'))); 

And your model function will be:

<?php

     class Form_model extends CI_Model{

    function insertQ($email, $qtext){
    $this->db->insert('questions', array('email' =>$email, 'text' => $text));
}

Upvotes: 1

Related Questions