php – 无法使用ajax将数据插入数据库

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – 无法使用ajax将数据插入数据库脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我是 jquery和ajax的新手,现在我很难在使用ajax和codeignITer将数据插入数据库时​​找到解决这个问题的方法.
所有错误都没问题,但是当表单上没有错误时,我收到数据库错误,所有输入都变为NULL.

调节

public function add () {

 $this->load->;model('user_model');
    $data => array (
      'First_name'      => $this->input->post['first_name'],'last_name'       => $this->input->post['last_name'],'active'          => $this->input->post['active'],'date_registered' => date('Y/m/d h:i:sa')
  );

  // assume validation rules are already set.
  if ($this->form_validation->run() == FALSE) {
   $result['message'] = validation_errors();
  } else {
   $result['data'] = $this->user_model->save($data);
  } 
 }

Ajax 1:

$(document).ready(function() { 
  $('#create-user').click( function(e) {
    VAR is_valid  = false;
    var form_id   = '#'+ $(this).parents('form').attr('id');
    // Validate required fields are not blank
    // do a js validation?

    // Apply action
    if(is_valid) {
      var add_result = do_submit(form_id);
    } else {
      $('#error-msg').htML(result.message); // if form is not valid
    }
  });
});

Ajax 2:

function do_submit(form_id) {
  var url         = $(form_id).attr("action");
  var ajax_result = false;
  var formData    = {};

  // Submit form using ajax
  ajax_result = $.ajax({
    tyPE: "POST",url: url,data: $(form_id).serialize(),dataType: 'json',success: function(result) {
      // return result; 
      //  do something
      console.LOG(result);
      if (result.data) {
        make_alert();
      }
    },error: function(textstatus) {
      /* Note: decide how all errors should be shown. */
      swal({
        title: "Error!",text: "Oops,something went wrong. Check fields and try again.",type: "error"
      });
    }
  });

  return ajax_result;
} // End do_submit()

解决方法

要在codeigniter中获取发布数据,我们使用

$this->input->post('field_name');

所以你需要将所有帖子[‘field_name’]更改为post(‘field_name’)

你的最终代码

$this->load->model('user_model');
        $data => array (
          'first_name'      => $this->input->post('first_name'),'last_name'       => $this->input->post('last_name'),'active'          => $this->input->post('active'),'date_registered' => date('Y/m/d h:i:sa')
      );

阅读https://www.codeigniter.com/user_guide/libraries/input.html

脚本宝典总结

以上是脚本宝典为你收集整理的php – 无法使用ajax将数据插入数据库全部内容,希望文章能够帮你解决php – 无法使用ajax将数据插入数据库所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。