Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

javascript - unable to retrieve data sent via ajax in controller Laravel 5.1

I am sending data via ajax to my controller as

$.ajax({
    url: 'test',
    type: 'POST',
    data: { id: sessionStorage.getItem('user_id') },
    dataType: 'json',
    contentType: "application/json; charset=utf-8"/*,
    success:function(id){
    alert(sessionStorage.getItem('user_id'));
}*/
});

and in the controller I am using

public function getUserMessages(){

        $id = Input::get('id');
        $messages = Message::where('message_by' , Auth::user()->id)->where('message_for',$id)->get();
        echo "id is ",$id;
        return $messages;
    }

I am getting nothing in $id. I have also tried $_POST['id'] which says undefined index id. How I can retrive the id value? $request->has('id') returns false too.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should use the Request class instead of Input:

public function getUserMessages(IlluminateHttpRequest $request){

        $id = $request->id;
        $messages = Message::where('message_by' , Auth::user()->id)->where('message_for',$id)->get();

        return $messages;
    }

Your ajax call doesn't work and will throw a 500 Server Error because you need to pass laravel's csrf token with it whenever you POST something. Create a meta tag at the top of your blade view like:

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

and get the value when you are doing the ajax call:

$.ajax({
    url: '/test',
    type: 'POST',
    data: { 
        id: sessionStorage.getItem('user_id'),
        _token:document.getElementsByName('_token_')[0].getAttribute('content') 
    },
    success:function(id){
    alert(id);
}
});

Most likely the success function in your ajax call will only alert [object Object], to get a better overview over whats returned, use

console.log(id);

instead.

You may also create an error function for the ajax call so that possible errors will be shown. Just do add

error: function(err){
    console.log(err);
}

after the success function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...