使用ajax将null插入数据库

时间:2017-02-06 18:59:41

标签: php jquery mysql ajax codeigniter

PHP新手。我的ajax很成功,但我无法弄清楚为什么我的MySQL数据库的每一列都会发布NULL。我的数据库有4列(name,cap,assigned_seating,open_seating)。这是一个简单的表格

//Model
class My_model extends CI_Model 
{
    function __construct()
    {
        parent::__construct();
    }    
    public function insert_data()
    {
        $data['name'] = $_POST['tableName'];
        $data['cap'] = $_POST['tableCap'];
        $data['assigned_seating'] = $_POST['assigned_seating'];
        $data['open_seating'] = $_POST['open_seating'];

        $this->db->insert('tables', $data);
    }  
}

//Controller
class Tables extends CI_Controller 
{
  function __construct()
  {
    parent::__construct();
    $this->load->model('My_model');
  }
  public function add()
  {
    $this->load->model('My_model');
    $this->My_model->insert_data();
  }
}

//Ajax
  $(".createTableButton").click(function(e) {
    e.preventDefault();
    var dataToSend = $('#myForm').serialize();
    $.ajax({
      url: "http://localhost/tableseating/tables/add",
      data: dataToSend,
      dataType: 'jsonp',
      method: 'POST',
      success: function()
      {
        console.log("Success");
      },
      error: function()
      {
        console.log("Error");
      }
    });

//HTML
  <form method="post" id="createTableForm" action="">

Table Name<input type="text" id="tableName" name="tableName" /><br>
Seat Cap<br><select type="select" id="tableCap" name="tableCap">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
  <option value="6">6</option>
  <option value="7">7</option>
  <option value="8">8</option>
  <option value="9">9</option>
  <option value="10">10</option>
  <option value="11">11</option>
  <option value="12">12</option>
  <option value="13">13</option>
  </select><br>

Table Type<br>
<input type="radio" id="openSeating" name="open_seating" checked="checked" required /> Open Seating<br>   
<input type="radio" id="assignedSeating" name="assigned_seating" required /> Assigned Seating<br><br>
<input type='submit' class='createTableButton btn btn-primary' value="Create"/>
        </form>  

1 个答案:

答案 0 :(得分:0)

您必须使用dataType:&#39; json&#39; (https://stackoverflow.com/a/4508215/7416478),试试这个:

class Tables extends CI_Controller 
{
  function __construct()
  {
    parent::__construct();
    $this->load->model('My_model');
  }
  public function add()
  {
$data = array(
      'name' => $this->input->post('tableName') ,
      'cap' => $this->input->post('tableCap') ,
      'assigned_seating' => $this->input->post('assigned_seating') ,
      'open_seating' => $this->input->post('open_seating') 
   );


   $this->My_model->insert($data);

  }
}

//模型

class My_model extends CI_Model 
{
    function __construct()
    {
        parent::__construct();
    }    
    public function insert_data($data)
    {
      $this->db->insert('tables', $data);
    }  
}