无法在codeigniter中提交数据

时间:2018-01-25 05:42:09

标签: codeigniter model controller

我试图在codeigniter中使用此代码提交数据,但无法提交数据并创建错误。

  

错误:POST http://localhost/managment/index.php/welcome/add 500(内部服务器错误)

signupform是我的注册表单的ID,其中包含6个字段并有一个提交按钮

ajax 我用.js扩展名保存了这个文件

$(document).on("submit", "#signupform", function (e) {
    e.preventDefault();
    //var view_id=$("#id_hid").val();
    //alert(view_id);
    $.ajax({
        type: "post",

        data: $('#signupform').serialize(),
        dataType: "JSON",
        url: "../welcome/add",
        success: function (data)
        {
            //var json=$.parseJSON(data);
            alert(data);
        }
    });
});

控制器

public function add() {
    //$data=array();
    $postData = array();
    //prepare post data
    $postData = array(
        'username' => $this->input->post('username'),
        'password' => $this->input->post('password'),
        'email' => $this->input->post('email'),
        'mobileno' => $this->input->post('mobileno'),
        'address' => $this->input->post('address')
    );

    // //insert post data

    $insert = $this->home_model->insert_form($postData);
    $data['msg'] = "data insert successfully";
    echo json_encode($data['msg']);
}

模型

function insert_form($data)
{   
    $insert=$this->db->insert('emp',$data);
    if($insert)
    {
        return $this->db->insert_id();
    }
    else
    {
        return false;
    }
    //echo  json_encode($data);
}

2 个答案:

答案 0 :(得分:2)

您的Javascript Ajax功能

      var frmData = $('#signupform').serialize();
      $.ajax({
        type:"post",

        data:{frmData:frmData},
        dataType: "JSON",
        url:"<?php echo base_url('index.php/your_controller_name/your_function_name')?>",       
        success:function(data)
         {

          }
        });

您的控制器功能

   public function add()
   {
        $postData=array();
        parse_str($this->input->post('frmData'),$postData);

        //prepare post data
        $postData = array(
            'username' => $postData['username'],
            'password' => $postData['password'],
            'email' => $postData['email'],
            'mobileno' => $postData['mobileno'],
            'address' => $postData['address']
        );       
   }

当您在java脚本中使用序列化时,您必须使用php的parse_str函数检索数据,然后您将从编码的字符串中获取准确的帖子数据。

答案 1 :(得分:1)

正如您在错误中提到的 错误:jquery.min.js:4 POST http://localhost/managment//index.php/welcome/add ,您可以看到网址的方向

错误

http://localhost/managment//index.php/welcome/add  
                          ^^

我应该为此做些什么

Change url:"../welcome/add",url:"http://localhost/managment/index.php/welcome/add",`

var base = <?php echo base_url() ?>
url: base+"index.php/welcome/add"

确保

application/config.php基础网址中应该是http://localhost/managment/

阅读 How do I PHP-unserialize a jQuery-serialized form?