Codeigniter始终返回错误消息

时间:2016-05-11 11:04:13

标签: php jquery ajax codeigniter

我尝试使用ajax转换codeigniter表单处理,然后在验证为false时显示验证错误但在我当前状态下,它总是抛出错误。请查看以下代码以供参考。

PHP:

 public function add () {

  $post_data = $this->input->post('formdata');
  $data = array (
    'identity' => $post_data ['email'],
    'password' => $post_data ['password'],
    'email' => $post_data ['email'],
    'group' => array($post_data['group_id']),
    'additional_data' => array (
      'first_name' => $post_data['first_name'],
      'last_name' => $post_data['last_name'],
      'active' => $post_data['active'],
      'date_registered' => date('Y/m/d h:i:sa')
      )
    );

    // custom error message
    $this->form_validation->set_message('alpha_dash_space', '%s appears to be invalid. Must contain only alphabets.');
    $this->form_validation->set_message('matches', '%s does not match the Confirm Password field. ');


    if ($this->form_validation->run() == TRUE) {
      $result['data'] = $this->ion_auth->register($data['identity'], $data['password'], $data['email'], $data['additional_data'], $data['group']);

    } else {
      $result['message'] = validation_errors();
    }
    echo json_encode($result);
 }

JS:

function submit_form (form_id) {
  var url      = $(form_id).attr("action");
  var formData = {};
  $(form_id).find("input[name]").each(function (index, node) {
    formData[node.name] = node.value;
  });
  $(form_id).find('select[name]').each(function (index, node) {
    formData[node.name] = node.value;
  });
  $(form_id).find('textarea[name]').each(function (index, node) {
    formData[node.name] = node.value;
  });
  $.ajax({
    type: "POST",
    data: {
      'formdata': formData
    },
    url: url,
    dataType: 'json', 
    success: function(result) {
      if (result.data) {
      console.log(success);
        swal({
        title: "Success!",
        text: "You've done it great!",
        type: "success"
      },
      function(){
        location.reload();
      });
      } else {
        $('#error-msg').html(result.message);
      }
    },

    error: function(data) {
      swal({
        title: "Error!",
        text: "Oops, something went wrong. Check and try again.",
        type: "error"
      });
    }
  });
}

注意:表单验证在config目录中设置。所以形式规则没有问题。除了我认为处理这个条件的jquery之外,一切都运行良好。

1 个答案:

答案 0 :(得分:1)

编辑如下:

if ($this->form_validation->run() == FALSE) {
       $result['message'] = validation_errors();
    } else {
       $result['data'] = $this->ion_auth->register($data['identity'],          
       $data['password'], $data['email'], $data['additional_data'],   
       $data['group']);
    }

您还有set_message但不是set_rules。如果您想使用form_validation库,则应设置一些规则。