draj30958 2017-10-17 03:12
浏览 81
已采纳

如何不在ajax提交codeigniter上重定向页面

So, i have a following ajax code and controller code, my problem is i want to insert comment withouth refreshing the page and not redirecting to another page, and it seems that whenever i hit btnCommentSubmit it is redirecting me to my controller page, how to prevent that?
Ps. The insertion is working
//AJAX CODE

$('#btnComment').click(function(e){

            var comment_identifier = $(this).data("value");
            var comment_by = $(this).data("id");
            $('#formAddComment').attr('action', '<?php echo base_url() ?>Discussion/addComment/'+comment_identifier+"/"+comment_by);
        });

        $('#btnCommentSubmit').click(function(){
            var url = $('#formAddComment').attr('action');
            var addCommentTxt = $('#addCommentTxt').val();
            $.ajax({
                type: 'post',
                url: url,
                data: {addCommentTxt:addCommentTxt},
                success: function(){
                    alert('success');
                },
                error: function(){
                    console.log(data);
                    alert('Could not add data');
                }
            });

        });
    });



//Controller code

public function addComment(){
        $cIden = $this->uri->segment(3);
        $cBy = $this->uri->segment(4);
        $data = array(
            "comment_identifier" => $cIden,
            "comment_by" => preg_replace('/[^a-zA-Z-]/', ' ', $cBy),
            "comment" => $this->input->post('addCommentTxt'),
            "comment_at" => time() 
        );  

        if ($this->Crud_model->insert('comments',$data)) {
            return true;
        }else{
            return false;
        }

    }
  • 写回答

3条回答 默认 最新

  • duanmu5641 2017-10-17 03:15
    关注

    Add e.preventDefault() in the beginning of your function:

    $('#btnCommentSubmit').click(function(e){
      e.preventDefault();
      ...
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 latex投稿显示click download
  • ¥15 请问读取环境变量文件失败是什么原因?
  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?