2014-10-02 61 views
1

我抓住從表單數據與的js序列化(),並添加數據到數據庫

var form_data = $('#form').serialize(); 

我得到例如 名=賬單&年齡= 133 &性別=男性

然後將此數據發送結果使用Ajax到控制器

$.ajax({ 
          type: "POST", 
          url: "<?php echo base_url().'admin/crud/change_table_data2'?>", 
          data: { 'form_data' : form_data}, 
          dataType: "json", 
          success: function(response) 
          { 
          alert(response); 
          } 
        }) 

在控制器我嘗試這一點,並將數據發送到模型,在那裏我嘗試將數據插入到數據庫

parse_str($_POST['form_data'], $add_array); //parse form inputa koji za koje je koriscenja js f-ja serialize() 

      $this->load->model('Data'); 
      $query = $this->Data->ajax_add($add_array); 

我的問題是,不知何故,當我使用的print_r($ add_array)我得到的AJAX頁面或成功部分沒有結果,所以我看不到陣列的結構,我不能弄明白哪裏是錯誤,可有人我寫的foreach類似這種

public function ajax_add($add_array) 
    { 
     foreach($add_array as $s) 
     { 
      foreach($s as $x) 
      { 
       (string)$data_sanitazed = htmlentities(mysql_real_escape_string($x)); 
       $data_insert = array('info' => $data_sanitazed); 
       $query = $this->db->insert('ci_crud', $data_insert); 
      } 
     } 
     return $query;    
    } 

diffrence name=bill&age=133&gender=male陣列是在這裏我只有一個科拉姆後來我增加了兩個

回答

0

不,你不需要把它放在另一個父架內。使用串行輸入直接:

var form_data = $('#form').serialize(); 
$.ajax({ 
    type: "POST", 
    url: "<?php echo base_url().'admin/crud/change_table_data2'; ?>", 
    data: form_data, // you can use it directly (name=bill&age=133&gender=male) 
    // dataType: "json", also commenting this worked for the OP as well. 
    success: function(response) { 
     alert(response); 
    } 
}); 

所以在PHP中,你可以使用它們裏面後,無需使用parse_str()

$_POST['name'] // directly access them 
$_POST['age'] 
$_POST['gender'] 
+0

問題是因爲我把數據類型: 「JSON」, – 2014-10-02 09:17:26

+0

@VladimirŠtus所以現在解決了? – Ghost 2014-10-02 10:14:15

+0

是的工作,我給你正確答案ty – 2014-10-02 11:38:50