php - codeigniter ajax表单验证 [英] php - codeigniter ajax form validation

查看:127
本文介绍了php - codeigniter ajax表单验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对jquery -ajax很新,我想要一些帮助,请加入CI。

Hi I’m quite new to jquery -ajax and I’d like some help please to join it with CI.

我在 href =http://www.youtube.com/watch?v=GrycH6F-ksY =nofollow>使用AJAX提交表单,我想将此功能添加到我的CodeIgniter网站。我想做的是当用户提交表单,如果有任何验证错误显示在每个输入字段(如本机ci过程中),或者如果这是不可能通过validation_errors()函数。如果没有错误在表单上方显示成功消息。

I have followed this tutorial on Submitting a Form with AJAX and I’d like to add this functionality to my CodeIgniter site. What I’d like to do is when the user submits the form, if there are any validation errors to show the individually on each input field (as in native ci process), or if this is not possible via validation_errors() function. If no errors occured to display a success message above the form.

到目前为止,我的代码如下:

Here's my code so far:

我的视图

 // If validation succeeds then show a message like this, else show errors individually or in validation_errors() in a list
<div class="alert alert-success">Success!</div>
<?php echo validation_errors(); //show all errors that ajax returns here if not individualy  ?>

<?php echo form_open('admin/product/add, array('class' => 'ajax-form')); ?>
<p>
    <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'); ?>
</p>
<p>
    <label for="brand">Brand</label>
    <input type="text" name="brand" value="<?php echo set_value('brand', $prod->brand); ?>" />
    <?php echo form_error('brand'); ?>
</p>
...  

我的控制器

 public function add($id){
           // set validation rules in CI native
           $rules = $this->product_model->rules;
           $this->form_validation->set_rules($rules);

           if ($this->form_validation->run() === true) {
                       // get post data and store them in db
          $data = $this->input_posts(array('product_name', 'brand', 'category_id', 'description'));
          $this->product_model->save($data, $id);
    // no errors - data stored - inform the user with display success-div
     } else {
    // validation failed - inform the user by showing the errors
     }
//load the view
$this->load->view('admin/products/add', $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) {
   // console.log(value);
   var obj = $(this),
    name = obj.attr('name'),
    value = obj.val();

   data[name] = value;
  });

  $.ajax({
   // see the (*)
   url: url,
   type: method,
   data: data,
   success: function(response) {
    console.log(response); // how to output success or the errors instead??
   }
  });
  return false; //disable refresh
 });
});  

如何通过ajax请求和显示传递我的验证结果(成功或发布错误)他们在我的看法?
从一些小的研究,我发现你可以使用单个控制器,既保留本地进程和ajax请求(而不是使用2控制器),但我的主要困难是,我不理解验证的结果如何通过js脚本并显示在我的视图上?请注意,我不希望在警告框中显示任何内容,而是显示结果的div或单独的错误(如果可能)。

How should I pass my validation results (either success or the post errors) throught the ajax request and display them on my view?? From some little research I did I've found that you can use a single controller, that holds both the native proccess and the ajax request (instead of using 2 controllers), but my main difficulty is, I don't understand how the results of the validation will pass through the js script and display them on my view?? Please note that I don't want to display anything on an alert box, instead show the results on a div or the errors individualy(if possible).

EDIT 我对我的应用程序进行了一些更改,以下是代码:

EDIT I did some changes to my application, here's the code so far:

控制器

public function manage($id = NULL){
    $this->load->library('form_validation');

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

    //fetch a single product or create(initialize inputs empty) a new one
    if (isset($id) === true) {
        $data['prod'] = $this->product_model->get($id);
        $data['attr'] = $this->attribute_model->get_by('product_id', $id, null, true);
    } else {
        $data['prod'] = $this->product_model->make_new();
        $data['attr'] = $this->attribute_model_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'));
            $this->product_model->save($data, $id);

            $status = true;
        } else {
            // validation failed
            $status = validation_errors();
        }
        if ( $this->input->is_ajax_request() ) {
            echo json_encode($status);
            exit;
        }
        redirect('admin/product');
    }
    //if (isset($_POST['attributes_settings'])) { the same thing here  }                

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

和js

success: function(response) {
    //console.log(response);
    if (data.status === true) {
        $('#ajaxResults').addClass('alert alert-success').html(response);
    } else {
        $('#ajaxResults').addClass('alert alert-error').html(response);
    };

}

但我遇到了一些问题


  1. 虽然我收到来自validation_errors()的错误消息作为警报错误,当没有错误时,我得到一个警报错误,警报成功。

2.我应该返回成功消息吗?例如。一条消息保存完成!。

2.how should I return the success message too? eg. a message saying "Saves were done!".


  1. 尽管在非ajax请求中,数据存储在数据库中,以防fo ajax不存储。任何想法可能出错?


推荐答案

HTML:

<div id="ajaxResults"></div>

Javascript ajax:

Javascript ajax:

 success: function(response) {
    $('#ajaxResults').text(response);
   }








您撰写的此脚本只有在验证成功时才是正确的?

this script you've wrote is only if the validation succeeds, right?

错误。每当您从服务器收到响应时(假设HTTP头为200),将会执行成功代码。您的JavaScript知道服务器是否有任何错误?

Wrong. The code in "success" gets executed any time you get a response back from the server (assuming the HTTP header is 200). Does your javascript knows if the server has any error for you? No.

您需要使用JavaScript来识别验证失败或成功。你有很多方法来做到这一点。其中一个可以是发送消息显示,后面跟一个0或1.

You need your JavaScript to recognize if the validation failed or succeeded. You have many ways to do that. One of these could be sending the message to display followed by a 0 or 1.

所以你的PHP看起来像:

So your PHP will looks like:

return "0 " . $errorMessage;

return "1 " . $successMessage;

,然后您的javascript应该识别if语句和 substring ,如果消息以0或1开头。

and your javascript should then recognize, with if statement and substring, if the message starts with 0 or with 1.

这篇关于php - codeigniter ajax表单验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆