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 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序