简体   繁体   English

如何在不重新加载页面的情况下使用 Laravel ajax 发布和获取评论?

[英]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?我尝试使用ajax发布数据它不起作用,我很困惑如何在不重新加载页面的情况下获取数据,有人可以帮助我吗?

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我还是不明白ajax是如何工作的,请帮忙

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

Update:更新:

Thanks for your answer, but i got another error in the javascript console when I submit comment:感谢您的回答,但是当我提交评论时,我在 javascript 控制台中遇到了另一个错误:

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) POST http://cafetawa01.app/comments 500(内部服务器错误)
k.cors.a.crossDomain.send @ jquery.min.js:4 k.cors.a.crossDomain.send @ jquery.min.js:4
n.extend.ajax @ jquery.min.js:4 n.extend.ajax @ jquery.min.js:4
(anonymous function) @ wifi-mengubah-segalanya-celebratemoment:425 (匿名函数)@wifi-mengubah-segalanya-celebratemoment:425
n.event.dispatch @ jquery.min.js:3 n.event.dispatch @ jquery.min.js:3
r.handle @ 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();您已分配$('#bodyComment').val(); as body but in the ajax call you are trying to pass作为body但在 ajax 调用中你试图通过

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.因此,jquery 将尝试查找导致"Uncaught RangeError: Maximum call stack size exceeded的变量bodyComment不可用bodyComment在评论中也提到了这一点。

So, you shall change your ajax call to所以,你应该改变你的ajax调用

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

Tip :提示 :

You shall check this in your console or in the networks tab in your browser您应该在控制台或浏览器的网络选项卡中进行检查

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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