duanmao2650 2018-07-09 22:12
浏览 51
已采纳

具有codeigniter验证的Ajax表单

I am trying to make ajax form validation work in codeigniter.

Form and ajax are both in views/products/addproducts,

  <script type="text/javascript"> 
    $(document).ready(function(){
        $("#submitProducts").click(function(e){
        e.preventDefault();
        var dataString = $("#add-products-bulk-form").serialize();
        var url="products/addproducts";
        $.ajax({
            type:"post",
            url:"<?php echo base_url() ?>"+url,
            dataType: 'json',
            data:dataString,
            success:function (res) {
                res=$.parseJSON(res);
                if($.isEmptyObject(res.error)){
                    alert(res.success);
                }else{
                    console.log("hasn't run form yet");
                }
            },  
      })
    })
    });    
    </script>

here is my Products controller:

public function addproducts()
    {
        $data['title'] = "Add Products";
        $this->load->view('templates/header', $data);
        $this->load->view('products/addproducts');
        $this->load->view('templates/footer');
        //form rules
        //$this->form_validation->set_rules('name[]', 'Product Name', 'required');
        $this->form_validation->set_rules('partnumber[]', 'Part number', 'required|is_unique[items.itemSKU]');
        //$this->form_validation->set_rules('msrp[]', 'MSRP', 'required');
        if ($this->form_validation->run() === FALSE)
        {
            echo "did not pass validation";
            $errors = validation_errors();
            echo json_encode(['error'=>$errors]);
        }
        else
        { 
            echo "did pass validation";
            $this->product_model->add_products();
            echo json_encode(['success'=>'Record added successfully.']);
        }
    }

I don't get any response when I click submit button if I keep the code above way. But if I get rid of line dataType:'json', I will get error

VM1679:1 Uncaught SyntaxError: Unexpected token d in JSON at position 0
    at Function.parse [as parseJSON] (<anonymous>)
    at Object.success (addproducts:140)
    at i (jquery-3.1.1.min.js:2)
    at Object.fireWith [as resolveWith] (jquery-3.1.1.min.js:2)
    at A (jquery-3.1.1.min.js:4)
    at XMLHttpRequest.<anonymous> (jquery-3.1.1.min.js:4)

If I get rid of both dataType:'json' and res=$.parseJSON(res), when I enter a duplicated product and click submit, and console.log(res), I get the following in the console, It did return the res and the source code of the whole page addproducts.

    did not pass validation{"error":"<p>The Part number field must contain a unique value.<\/p>
"}<!DOCTYPE html>
<html lang="en">
<head>

I did not paste the whole source code here. and res.success will alert undefined.

I have been stuck for days, please help. I will provide more details if needed. Thanks!

  • 写回答

2条回答 默认 最新

  • dongluo9156 2018-07-09 22:21
    关注

    To clean up my earlier comment...

    public function addproducts()
    {
    
        //form rules
        //$this->form_validation->set_rules('name[]', 'Product Name', 'required');
        $this->form_validation->set_rules('partnumber[]', 'Part number', 'required|is_unique[items.itemSKU]');
        //$this->form_validation->set_rules('msrp[]', 'MSRP', 'required');
    
        header('Content-Type: application/json');
    
        if ($this->form_validation->run() === FALSE)
        {
    
            $this->output->set_status_header(400);
            $errors = validation_errors();
            echo json_encode(['error'=>$errors]);
        }
        else
        {
            $this->output->set_status_header(200);
            $this->product_model->add_products();
            echo json_encode(['success'=>'Record added successfully.']);
        }
    }
    

    Now you can use the success callback to listen for a successful response and the error callback to listen for an error response...

    <script type="text/javascript">
        $(document).ready(function(){
            $("#submitProducts").click(function(e){
                e.preventDefault();
                var dataString = $("#add-products-bulk-form").serialize();
                var url="products/addproducts";
                $.ajax({
                    type:"post",
                    url:"<?php echo base_url() ?>"+url,
                    dataType: 'json',
                    data:dataString,
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert(jqXHR.responseJSON.error);
                    },
                    success: function (data, textStatus, jqXHR) {
                        alert(jqXHR.responseJSON.success);
                    }
                });
            });
        });
    </script>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵