Monday, August 10, 2015

write comment by ajax post using codeigniter with recaptcha

PHP

public function write_comment($article_id) {
        $this->xhr_protect();

        $this->load->config('recaptcha');
        $secret_key = $this->config->item('secret_key', 'recaptcha');
        require_once (APPPATH . 'libraries/recaptcha/recaptchalib.php');

        $cf = $this->input->post('recaptcha_challenge_field');
        $rf = $this->input->post('recaptcha_response_field');
        $title = $this->input->post('title');
        $message = $this->input->post('message');
       
        if (empty($title) || empty($message)) {
            $this->error('Нэр эсвэл сэтгэгдэл хоосон байна!');
        }

        $resp = recaptcha_check_answer($secret_key
                , $this->input->ip_address()
                , $cf
                , $rf);

        if (!$resp->is_valid) {
            $this->error("Шалгах хэсэг буруу байна! (reCAPTCHA said: " . $resp->error . ")");
        }

        $article = $this->article_model->get($article_id);
        if (empty($article)) {
            show_404();
        } else {
            $this->load->model('comment_model');

            $comment = array();
            $comment['title'] = html_escape($title);
            $comment['message'] = html_escape($message);
            $comment['approved'] = 1;
            $comment['ipaddress'] = $this->input->ip_address();
            $comment['createddate'] = utc_datetime();

            $comment['id'] = $this->comment_model->save($comment);

            $article_comment = array('article_id' => $article['id'], 'comment_id' => $comment['id']);
            $this->article_comment_model->save($article_comment);

            $comment['date'] = date_descr($comment['createddate']);
            $this->success('Амжилттай!', array('data' => $comment));
        }
    }


JS



<script type="text/javascript">

        function CreateCaptcha() {
            Recaptcha.create('<?php echo $site_key; ?>', 'recaptcha', {theme: "red"});
        }
        $.getScript('http://www.google.com/recaptcha/api/js/recaptcha_ajax.js', CreateCaptcha);
        $('.post-reply-entry button').click(function (event) {
            event.preventDefault();
            var arr = $('#write_comment').postItems();
            var params = {};
            for (var i = 0; i < arr.length; i++) {
                params[arr[i].name] = arr[i].value;
            }
            $.ajax({
                url: '<?php echo site_url('forum/write_comment/' . $article['id']); ?>',
                type: 'post',
                dataType: 'json',
                data: params,
                cache: false,
                success: function (result) {
                    CreateCaptcha();
                    if (result.success) {
                        $('#write_comment').find('[name="message"]').val();
                        var comment = (result.data);
                        var s = '<div class="reply-post-one"><div class="reply-user"><span class="username">' + comment.title;
                        s += '</span><span class="date">' + comment.date + '</span></div><p>' + comment.message + '</p></div>';
                        $(s).prependTo($('#forum_comment_list'));
                    } else {
                        alert(result.message);
                    }
                },
                error: function (jqXhr, textStatus, errorThrown) {
                    alert("Error '" + jqXhr.status + "' (textStatus: '" + textStatus + "', errorThrown: '" + errorThrown + "')");
                }
            });
        });
        $('a[href="#write_comment"]').click(function (event) {
            event.preventDefault();
            $('.site-container').animate({
                scrollTop: $($(this).attr('href')).offset().top - 100
            }, 1000, 'swing');
            return false;
        });

    </script>

No comments: