简体   繁体   中英

Laravel 5.1 - Pass variable from ajax to my controller

i have a list of comments with ajax but it doesnt work:

CommentList.js

 $(document).ready(function(){

        var tablaDatos = $("#comentos");
        var dato2= $("#article_id").val();
        var route = "http://localhost:8000/commentList/"+dato2;

        $.get(route, function(res){

            $(res).each(function(key,value){
                tablaDatos.append(value);

            });
        });

    });

article.blade.php

@foreach($comments as $comment)
    <li id="comentos">
       <input type="hidden" name="article_id" id="article_id" value="{{$article->id}}">
   </li>
@endforeach

FrontController.php

public function listing($id)
    {
        // store the comments list
        $list = [];

        // retrieve comments
        $article = Article::where('article_id', $id)->first();
        $comments = Comment::where('article_id', $article->id)->get();

        // render each comment and store it
        foreach ($comments as $comment) {
            $html = view('layouts.comment-template')
                ->with('comment', $comment)
                ->render();

            $list[] = $html;
        }

        // return a JSON array of the comments list
        return response()->json($list);

    }

I passed "$article" to my view "article.blade.php", so "$article->id" work well

I think that problem is that $article->id input doesnt pass to my controller, maybe a problem with commentList.js ( wrong route?)

Route

Route::get('commentList/{id}','FrontController@listing');

There is a best way to pass my variable id?

哦,我检查我的控制台,错误是Article :: where('article_id',$ id),正确的是Article :: where('id',$ id)。

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