Felix Maxime Felix Maxime - 2 months ago 7
Ajax Question

Sending data to a controller with ajax in laravel

I'm trying to send a simple POST request data to a controller, but with ajax. Nothing fancy, I simply want to send data to my controller without the page redirecting/refreshing.

EDIT: Updated all of the code to what it currently is

In header

<meta name="csrf-token" content="{{ csrf_token() }}" />
<script>var host="{{url()}}"</script>


Route

post('/messages/unread', '\CommendMe\Http\Controllers\MessageController@getReadRequest');


Markup

<div class="accordion messageAccordion getRequestReadMessage" data-value="{{$message->id}}">


Script

$('.getRequestReadMessage').click(function() {
$readValue = $(this).attr('data-value');
$token = $('meta[name=csrf-token]').attr("content");
$.ajax({
type: "POST",
url: host + '/messages/unread',
data: {readValue: $readValue, _token:$token},
});
});


Controller

public function getReadRequest(Request $request)
{
dd(Input::get("readValue"));
}

Answer

Since you're using the method POST, you have to send it a _token, you are probably getting a token mismatch error.

On your header, put this:

<meta name="csrf-token" content="{{ csrf_token() }}" />

On JS

$('.getRequestReadMessage').click(function() {
    $readValue = $(this).attr('data-value');
    $token     = $('meta[name=csrf-token]').attr("content");
        $.ajax({
        type: "POST",
        url: host + 'messages/unread',
        data: {readValue: $readValue, _token:$token},
    });
});

Your route seems a bit off, though. update it to: post('/messages/unread', '\CommendMe\Http\Controllers\MessageController@getReadRequest');

====EDIT=====

Additionaly, i see that you have that div around a form field, since you are using ajax, its not necessary.

<div class="accordion messageAccordion getRequestReadMessage" data-value="{{$message->id}}">

What i did was remove the form field and the hidden input, also i removed the type=submit attribute, since its not a button in a form. I algo changed the value attribute in the div, to data-value. Change your JS to this:

$readValue = $(this).attr('data-value');

EDIT 2

$('.getRequestReadMessage').click(function() {
    $readValue = $(this).attr('data-value');
    $token     = $('meta[name=csrf-token]').attr("content");
    $.ajax({
        type: "POST",
        url: host + '/messages/unread',
        data: {readValue: $readValue, _token:$token},
    }).success(function (res){
        alert('it work! :D');
    });
});
Comments