StealthTrails
StealthTrails

Reputation: 2415

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.

Upvotes: 1

Views: 2169

Answers (3)

FGDeveloper
FGDeveloper

Reputation: 1050

Have you a route for AJAX requests? (I don't see it.)

Please try following code:

In your AJAX code:

$.ajax({
    type: "POST",
    url: "{{ route('ajax_route') }}",
    data: { _token:  "{{ csrf_token() }}", data: "sample data" },
    success: function(data){
        $(".result").html(data);
    },
    dataType: "json"
});

In your controller code:

public function ajaxAction(Request $request){
  if ($request->isXmlHttpRequest() && $request->isMethod('post')) {
    $data = $request->input('data', null);
    echo json_encode($data);
  }
}

In your route code:

Route::post('/ajax_route', ['as' => 'ajax-action', 'uses' => 'YourController@ajaxAction']);

Upvotes: 0

mdamia
mdamia

Reputation: 4557

The problem is that you are setting the application content as json, You don't need to set the content.

jQuery ajax

contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')

$.ajax({
    url: 'test',
    type: 'POST',
    data: { id: sessionStorage.getItem('user_id') },
    dataType: 'json',

    success:function(data){
         console.log(data); // always good to output content for debugginn
    }
});

Hope this help. Your ajax should work now.

Upvotes: 0

baao
baao

Reputation: 73241

You should use the Request class instead of Input:

public function getUserMessages(\Illuminate\Http\Request $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.

Upvotes: 3

Related Questions