xslibx
xslibx

Reputation: 4349

Reload part of page, not whole page, once Ajax is successful. Laravel

I'm using Laravel 4 for my project. I have a "newsfeed" of posts. Each post can be commented on. When a user comments on a post the page reloads and the new comment is shown in the comment box. How ever i do not want the whole page to reload. So, I'm able to submit the post using ajax. I submit the form and prevent the page from refreshing. However, now I don't know how to get the comment to appear on the post without manually refreshing the page?

Here is my route for posting comments:

Route::post('post/{id}/comment', ['as' => 'commentPost', 'uses' => 'CommentsController@postComment']);

The controller that posts this comment to the DB:

public function postComment()
 {
     extract(Input::only('user_id', 'resource_id', 'body'));
     $this->execute(new PostCommentCommand($user_id, $resource_id, $body));

     return Redirect::back();
 }

Im using a command bus that ultimately saves the comment to the DB like this:

public function leaveComment($user_id, $resource_id, $body)
{
    $comment = Comment::leavePostComment($resource_id, $body);

    User::findOrFail($user_id)->comments()->save($comment);

    return $comment;
}

Comment model:

public static function leavePostComment($resource_id, $body)
{
    return new static([
        'resource_id' => $resource_id,
        'body' => $body
    ]);
}

Here is the view that loads the comment box (contains all comments belonging to the post and a type box for posting new comments. I use JS to post the comment when user hits "enter/return" key):

<div class="comment-box-container">
<div class="comment-box">
@if ($type->comments)
    @foreach ($type->comments as $comment)

<div class="user-comment-box">

<div class="user-comment">
    <p class="comment">
    <!-- starts off with users name in blue followed by their comment-->
        <span class="tag-user"><a href="{{ route('profile', $comment->owner->id) }}">{{ $comment->owner->first_name }}&nbsp;{{ $comment->owner->last_name }}</a>&nbsp;</span>{{ $comment->body }}
    </p>
    <!-- Show when the user posted comments-->
    <div class="com-details">
    <div class="com-time-container">
        &nbsp;{{ $comment->created_at->diffForHumans() }} ·
    </div>
    </div>

  </div><!--user-comment end-->
</div><!--user-comment-box end-->
@endforeach
@endif

<!--type box-->
    <div class="type-comment">
        <div class="type-box">
        {{ Form::open(['data-remote', 'route' => ['commentPost', $id], 'class' => 'comments_create-form']) }}
            {{ Form::hidden('user_id', $currentUser->id) }}
            {{ Form::hidden($idType, $id) }}
            {{--{{ Form::hidden('user_id', $currentUser->id) }}--}}
            {{ Form::textarea('body', null, ['class' =>'type-box d-light-solid-bg', 'placeholder' => 'Write a comment...', 'rows' => '1']) }}
        {{ Form::close() }}
        </div><!--type-box end-->
    </div><!--type-comment-->


</div><!--comment-box end-->

and here is my Javascript for the ajax:

(function(){

$('form[data-remote]').on('submit', function(e){
    var form = $(this);
    var method = form.find('input[name="_method"]').val() || 'POST';
    var url = form.prop('action');

    $.ajax({
        type: method,
        url: url,
        data: form.serialize(),
        success: function() {

              ** I DON'T KNOW WHAT TO PUT HERE TO MAKE THE 
              COMMENT-BOX RELOAD AND DISPLAY THE NEWLY 
              POSTED COMMENT **

            }
    });

    e.preventDefault();
});
})();

Please note I'm very new to JavaScript and even newer to Ajax. Any help would be greatly appreciated!!

Upvotes: 2

Views: 3913

Answers (1)

tacone
tacone

Reputation: 11441

Something along the lines of:

$.ajax({
    type: method,
    url: url,
    data: form.serialize(),
    success: function(data) {
        // use a temp wrapper element to workaround weak jQuery HTML parser
        var tmp = $('<div>');
        tmp.html(data);
        // update the comment box with the new one
        $('.comment-box').html(tmp.find('.comment-box').html());
        // update the form (so it eventually shows validations errors)
        // don't forget to empty it via PHP if the submission was
        // successful
        $('.type-box').html(tmp.find('.type-box').html());
        tmp.destroy();
    }
});

Upvotes: 1

Related Questions