【问题标题】:CodeIgniter - Ajax validation not working correct and not storing data in databaseCodeIgniter - Ajax 验证无法正常工作且未将数据存储在数据库中
【发布时间】:2013-07-19 10:22:41
【问题描述】:

我需要一些帮助。

  1. 从我的测试到现在,我得到了这些:
    • 如果验证失败 - 我认为的 div #ajaxResults 会获取类 alert-error 并显示错误(如预期的那样)。
    • 如果验证成功 - div #ajaxResults 获取类 alert-error(非预期)并显示 true(如预期)。

当有 ajax 请求时,我想做的是:

  • 如果验证成功 - 返回带有类 alert-success(bootstrap) 的 div #ajaxResults 并显示一条消息“数据已成功存储在数据库中”。我不知道我应该如何返回以及来自控制器的消息。
  • 如果验证未能显示带有验证错误的类警报错误的 div #ajaxResults。 (原样)

2.我还注意到,在非 ajax 请求的情况下,数据存储在数据库中,但在 ajax 请求的情况下则不存储。如何解决此问题以使其正常工作?

这是我的控制器

public function manage($id = NULL){
    $this->layout->add_includes('js/ckeditor/ckeditor.js')->add_includes('js/ajax_scripts.js');
        $this->load->library('form_validation');

$data['categ'] = $this->category_model->with_parents();

//fetch a single product or create a new one
if ( isset($id) ) {
    $data['prod'] = $this->product_model->get($id);
    $data['attr'] = $this->attributes_model->get_by('product_id', $id);
} else {
    $data['prod'] = $this->product_model->make_new();
    $data['attr'] = $this->attribute_model->make_new();
} 
if ( isset($_POST['general_settings']) ) {
    if ($this->form_validation->run('product_rules') === true) {
        // get post inputs and store them in database
        $data = $this->product_model->input_posts(array('product_name', 'brand', 'category_id', 'general_description','visible'));
        $this->product_model->save($data, $id);

        $result = array('status' => 200, 'message' => 'data stored in database successfully');
    } else {
        // validation failed
        $result = array('status' => 400, 'reason' => validation_errors());
    }
    if ( $this->input->is_ajax_request() ) {
        echo json_encode($result);
        exit;
    }
    $this->session->set_flashdata('message', $result);
    redirect('admin/product');
}

// if ( isset($_POST['attribute_settings']) ) { same goes here }



// load the view
$this->load->view('admin/products/manage', $data);
}

这是我的 js 脚本

 $(document).ready(function () {
    $('form.ajax-form').on('submit', function() {
        var obj = $(this), // (*) references the current object/form each time
            url = obj.attr('action'),
            method = obj.attr('method'),
            data = {};

        obj.find('[name]').each(function(index, value) {
            var obj = $(this),
                name = obj.attr('name'),
                value = obj.val();

            data[name] = value;
        });
        // console.log(data);

        // data.general_settings = 1;
        $.ajax({ // see the (*)
            url: url,
            type: method,
            data: data,
            dataType: 'json',
            success: function(response) {
                //console.log(response);
                $('#ajaxResults').removeClass('alert alert-success alert-error');
$('.control-group').removeClass('error warning error info success');
                if (response.status == 200) {
                    $('#ajaxResults').addClass('alert alert-success').html(response.message);
$('.control-group').addClass('success'); // ** apply it only on valid fields
                } else {
                    $('#ajaxResults').addClass('alert alert-error').html(response.reason);
$('.control-group').addClass('error'); // ** apply it only on invalid fields
                }
            }
        });
        return false; //disable refresh
    });
});

我的一个表单,在视图中带有 .ajax-form 类

<?php echo form_open('admin/product/manage/'.$prod->product_id, array('class' => 'ajax-form')); ?>
    <div class="control-group">
    <label class="control-label" for="product_name">Product *</label>
    <input type="text" name="product_name" value="<?php echo set_value('product_name', $prod->product_name); ?>" />
    <?php echo form_error('product_name'); ?>
</div>
    <div class="control-group">
    <label class="control-label" for="brand">Brand</label>
    <input type="text" name="brand" value="<?php echo set_value('brand', $prod->brand); ?>" />
    <?php echo form_error('brand'); ?>
</div>
// apply same to all my fields
    <p>
         <label for="category_id">Category *</label>
         <?php echo form_dropdown('category_id', $categ);
               echo form_error('category_id');
            ?>
    </p>
    <p>
          <label for="general_description">General Description</label>
          <textarea class="ckeditor" name="general_description" rows="10" cols="250"><?php echo set_value('general_description', $prod->general_description); ?></textarea>
           <?php echo form_error('general_description') . PHP_EOL; ?>
    </p>
    <p>
          <label for="visible">Visible</label>
          <select name="visible" class="span1">
              <option value="0">No</option>
             <option value="1">Yes</option>
          </select>
    </p>
    <p>
        <button class="btn btn-primary" type="submit" name="general_settings">Ok</button>
    </p>
<?php echo form_close() . PHP_EOL; ?>

任何帮助将不胜感激。

【问题讨论】:

    标签: php database codeigniter validation jquery


    【解决方案1】:
    • 据我了解,您需要这样的东西(我只放了代码片段)。

    控制器:

    if($this->form_validation->run('product_rules') === true){
        //your code will be here
        $result = array(
            'status' => 200, 'message' => 'data stored in database successfully'
        );
    }
    else{
        $result = array('status' => 400, 'reason' => validation_errors());
    }
    if ( $this->input->is_ajax_request()){
        echo json_encode($result);
        exit;
    }
    else{
        $this->session->set_flashdata('message', $result);
        redirect('admin/product');
    }
    

    Ajax 函数:

    data.general_settings = 1;
    $.ajax({
        url: url,
        type: method,
        data: data,
        dataType: 'json',
        success: function(response) {
            $('#ajaxResults').removeClass('alert alert-success alert-error');
            if(response.status == 200){
                $('#ajaxResults').addClass('alert alert-success').html(response.message);
            }
            else{
                $('#ajaxResults').addClass('alert alert-error').html(response.reason);
            }
        }
    });
    
    • 您是否在 firebug 中看到同样的 ajax 请求错误?

    【讨论】:

    • 我做了您的更改,似乎有效,但仍有一些问题。如果第一次验证失败,它会按预期返回警报错误中的错误,但如果我再次正确提交表单,它会再次在警报错误中显示成功消息。其次,在 Ajax-request 场景中,数据不存储在数据库中,而在非 ajax 场景中,数据不存储在数据库中。我不知道出了什么问题
    • 1.请查看 success() 函数,我已经更新了它。 2. 您在 firebug 中看到任何错误吗?
    • @2.没有错误。如果验证成功,则显示成功消息,否则显示验证错误
    • 尝试将messagesession-&gt;flashdata转储到admin/product。是否存在任何错误?
    • 这将在非 ajax 请求中,对吧?我该怎么做?
    猜你喜欢
    • 2019-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多