-2

I'm using phalcon framework and In my blog i want to append comments with ajax but the problem is in my controller query. i don't understand how to return query data to view with ajax. my current query script return entire hole html page but i need only commented data. someone please help

[Controller]

public function detailsAction($id)
{
    $blog = Blogs::findFirstByid($id);

#Comments Retrieve
    $coment = Comments::find();
}

public function bCommentAction()
{
    if($this->session->has('uname'))
    {
        if($this->request->isPost() == true || $this->request->isAjax() == true) 
        {
            $comments = new Comments();
            $comments->cauthor = trim($this->session->get('uname'));
            $comments->bcoment = trim($this->request->getPost('bComent'));
            $comments->entry_id = trim($this->request->getPost('postId'));
            if(!$comments->create() == true)
            {
                $this->flashSession->success("SUCCESS:: Comments inserted");
                return $this->response->redirect($this->request->getHTTPReferer());
            }
            else
            {
    return $this->response->setJsonContent(['bcoment' => $comments->bcoment, 
    'cauthor' => $comments->cauthor, 'entry_id' => $comments->entry_id]);
            }
        }
        else{echo('Request is Not ajax!');}
    }
    else
    {
        echo('<script>alert("You are not loggedin!");</script>');
    }
    $this->view->disabled();
}

[Jquery]

$('#blogComment').submit(function(e){
    e.preventDefault();
    var blogComent = $("input[name='bComent']").val();
    var postsId = $("input[name='idPost']").val();
    $.ajax({
        url:'blog/bComment/',
        type: 'POST',
        cache: false,
        data: {'postId':postsId,'bComent':blogComent},
        success: function(data){ 
            $('#datax').append('<div class="bcom">'+json.stringify(data)+'</div>').fadeIn(500);
        }
    });
    return false;
});

[View]

<div id="datax">
{% for coment in comented %}
{% if coment.entry_id === detail.id %}
<div class="bcom">
{% for user in logged %}
{% if coment.cauthor === user.uname %}
{{ image('data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=',"alt": "Some Photo","data-src":"uploads/users/"~user.image,"title":""~user.uname,"class":"comentedId") }}
{% endif %}
{% endfor %}
<b>{{coment.cauthor}}</b><br/>
{{coment.bcoment}}
</div>
{% endif %}
{% endfor %}</div>

Output looks like image below:

enter image description here

Styled Bee
  • 141
  • 1
  • 12

3 Answers3

0

Try moving this line to the top of your action.:

$this->view->disabled();

By the looks of it with your current code, it never gets fired.

Also, I would consider rewriting this block:

    if(!$comments->create() == true)
    {
        $this->flashSession->success("SUCCESS:: Comments inserted");
        return $this->response->redirect($this->request->getHTTPReferer());
    }
    else
    {
        return $this->response->setJsonContent(['bcoment' => $comments->bcoment, 'cauthor' => $comments->cauthor, 'entry_id' => $comments->entry_id]);
    }

Perhaps something as simple as:

if(!$comments->create()){
    return $this->response->setJsonContent(['status' => 'error']);
) else {
    return $this->response->setJsonContent([
        'status' => 'success',
        'payload' => [
            'bcoment' => $comments->bcoment, 
            'cauthor' => $comments->cauthor, 
            'entry_id' => $comments->entry_id
        ]
    ]);
}
Armon Bigham
  • 339
  • 2
  • 14
0

Try like This :

$('#comentSave').on('click', function(e) {
    e.preventDefault();
    var coment = $('.comnt').val();
    var cid = $('.pid').val();
    $.ajax({
    type:'POST',
    url:'blog/comments',
    data:{'bcoment':coment,'postId':cid},
    beforeSend: function(){$('.loader').html('Processing...');}
    }).done(function(resp){
        console.log(typeof resp);
        resp = JSON.parse(resp);
        resp.forEach(function(value){
            if(value.e === 'e1'){alert('Insertion Failed!');}
            if(value.e === 'e2'){alert('You are not authorized!');}
            if(value.e === 'e3'){if(value.uname === value.cauthor){var cdata = 'bcomBase';}else{cdata = 'bcom';}
                $('#datax').append('<div class="'+cdata+'"><img src="uploads/users/'+value.userimg+'"><b>'+value.cauthor+'</b><br/>'+value.bcoment+'</div>');
                $('.comentcount').text(value.count);
            }
        });
        $('#blogComment')[0].reset() || $('.comnt').val('');
    }).fail(function(){ alert('Reload & try again..!'); }).always(function(){});
    return false;
});


public function commentsAction()
{
$this->view->disable();
if(!empty($this->session->get('uname')))
{
    $comments = new Comments();
    $comments->cauthor = $this->session->get('uname');
    $comments->bcoment = $this->request->getPost('bcoment');
    $comments->entry_id = $this->request->getPost('postId');
    $resData = array();
    if($comments->save() === true)
    {
        $data = Blogs::findFirstByid($this->request->getPost('postId'));
        $cc = Comments::countByentry_id($this->request->getPost('postId'));
        $user = Users::findFirstByid($this->session->get('id'));
        $query = Comments::findByid($comments->id);
        foreach($query as $q){$resData[] = array('bcoment' => $q->bcoment, 'cauthor' => $q->cauthor, 'entry_id' => $q->entry_id, 'count' => $cc, 'userimg' => $user->image, 'e' => 'e3', 'uname' => $data->blog_author);}
        echo(json_encode($resData));                
    }
    else{$resData[] = array('e' => 'e1');echo(json_encode($resData));}
}
else{$resData[] = array('e' => 'e2');echo(json_encode($resData));}
}
munaz
  • 166
  • 2
  • 14
-1

You can get only the text of the comment and do an "echo" of it as a json file. Do a research about returning json from the server. There's a lot of references on the internet about how to parse an php array to json string and retrieving this for the ajax request.

And, you'll have to change your javascript's ajax request too, in order to take that json string and parse it to an javascript array.