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 求小游戏炸弹人中关于敌人的C++代码
  • ¥15 拿到这个服务器最高权限有偿
  • ¥50 来个抓app跳转支付宝转链接的
  • ¥15 remotes安装提示没有description文件
  • ¥15 AttributeError: 'NoneType' object has no attribute 'drop_duplicates'报错
  • ¥15 以下代码,运行结果报错
  • ¥15 Vivado仿真数据出错
  • ¥15 银河麒麟不支持vant等前端框架怎么办?
  • ¥15 vue3的子组件在父页面调用不显示不生效问题
  • ¥15 cadence PEX