2

I'm new to Laravel. I'm attempting a simple Ajax request however I get the following error message. What does this mean?

{message: "", exception: "Symfony\Component\HttpKernel\Exception\HttpException",…} exception: "Symfony\Component\HttpKernel\Exception\HttpException" file: "C:\MAMP\htdocs\project_21_my_laravel_website\vendor\laravel\framework\src\Illuminate\Foundation\Exceptions\Handler.php" line: 204 message: ""

index.blade.php

<div class="myTestLink">my Test Link</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $(".myTestLink").click(function(){
        $.ajax({
            method: 'post',
            dataType: 'json',
            url: 'insert-ajax',
            success: function (data)
            {
                alert(data);
            }
        });

    });
});
</script>

web.php

Route::post('/insert-ajax', 'myTestController@testingsomething');

myTestController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class myTestController extends Controller
{
    public function testingsomething()
    {
        return "hello";
    }
}

2 Answers 2

4

You must use CSRF token.

Please add the meta tag within the head tag in the blade file.

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

Then change your javascript like this.

$(document).ready(function () {
        $(".myTestLink").click(function(){
            $.ajax({
                method: 'post',
                dataType: 'json',
                url: 'insert-ajax',
                beforeSend: function (request) {
                        return request.setRequestHeader('X-CSRF-Token', $("meta[name='csrf-token']").attr('content'));
                    },
                success: function (data)
                {
                    console.log(data)
                }
            });

        });
}
Sign up to request clarification or add additional context in comments.

1 Comment

I had used that but still issue is there
1

Please add the meta tag within the head tag in the blade file.

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

Then in the scripts section please add the following:

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

For reference you can go through this the documentation doc. Hope this helps and solves the issue. Thanks.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.