简体   繁体   中英

How to post and get comment using laravel ajax without reload page?

I try to post data using ajax it not work and i'm confuse how to get the data without reload the page, could anyone help me?

Route:

Route::get('comments', 'CafetawaController@getComments');
Route::post('comments', 'CafetawaController@postComments');

Controller:

public function postComments(Request $request)
{
    if($request->ajax()){
        $comment = new Comment();
        $comment->userid =  Input::get( 'userid' );
        $comment->mediaid = Input::get( 'mediaid' );
        $comment->body = Input::get( 'bodyComment' );
        $comment->date = Carbon::now();
        $comment->type = "media";
        $comment->save();

        $response = array(
            'status' => 'success',
            'msg' => 'Setting created successfully',
        );
        return Response::json($response);
        return 'yes';
    }else{
        return 'no';
    }
}

View:

{!! Form::open(array('url'=>'comments','method'=>'POST', 'id'=>'frmComments')) !!}
   <table width="100%">
      <tbody>
         <tr>
            <td valign="top" style="padding-right:10px">
               {!! Html::image('images/no-profile.png', null, array('class' => 'img-responsive img-rounded media-preview')) !!}
            </td>
            <td valign="top" width="100%">
               {!! Form::hidden('mediaid', $list->id, array('id' => 'mediaid')) !!}
               {!! Form::hidden('userid', $list->userid, array('id' => 'userid')) !!}
               {!! Form::textarea('bodyComment', null, array('class'=>'form-control elastic', 'id'=>'bodyComment', 'rows'=>'5', 'placeholder' => 'Comments here...')) !!}
            </td>
         </tr>
         <tr>
            <td colspan="2" align="right" style="padding-top:10px">
               {!! Form::submit('Submit', array('name'=>'submit', 'class'=>'btn btn-primary', 'id' => 'btnComments')) !!}
            </td>
         </tr>
      </tbody>
   </table>
{!! Form::close() !!}

And here is my script:

    $('#frmComments').on('submit', function(e) {
        e.preventDefault();
        var body = $('#bodyComment').val();
        var mediaid = $('#mediaid').val();
        var userid = $('#userid').val();
        $.ajax({
            type: "POST",
            url: 'http://cafetawa01.app/comments',
            data: {body:bodyComment, mediaid:mediaid, userid:userid},
            success: function(msg) {
                a$("body").append("<div>"+msg+"</div>");
            }
        });
    });

When i click submit button, i got "Uncaught RangeError: Maximum call stack size exceeded"

I still don't understand how ajax works, please help

===========================================================================

Update:

Thanks for your answer, but i got another error in the javascript console when I submit comment:

Head:

<meta name="_token" content="{!! csrf_token() !!}">

Body:

<script type="text/javascript">
$.ajaxSetup({
   headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
</script>

Ajax:

    $('#frmComments').on('submit', function(e) {
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: '/comments',
            data: {body:$('#bodyComment').val(), mediaid:$('#mediaid').val(), userid:$('#userid').val()},
            success: function(msg) {
                $("body").append("<div>"+msg+"</div>");
            }
        });
    });

POST http://cafetawa01.app/comments 500 (Internal Server Error)
k.cors.a.crossDomain.send @ jquery.min.js:4
n.extend.ajax @ jquery.min.js:4
(anonymous function) @ wifi-mengubah-segalanya-celebratemoment:425
n.event.dispatch @ jquery.min.js:3
r.handle @ jquery.min.js:3

Here is my console screenshot

anyone can help?

The issue here

var body = $('#bodyComment').val();
              ^^^^^^^^^^^^

You have assigned the $('#bodyComment').val(); as body but in the ajax call you are trying to pass

data: {body:bodyComment, mediaid:mediaid, userid:userid}
            ^^^^^^^^^^^  

So, the jquery will try to look for the variable bodyComment which is not available that results in "Uncaught RangeError: Maximum call stack size exceeded . Jan also mentioned this in comment.

So, you shall change your ajax call to

data: {body:body, mediaid:mediaid, userid:userid}

Tip :

You shall check this in your console or in the networks tab in your browser

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM