Pe Dore
Pe Dore

Reputation: 9

Laravel Ajax runs in 500 Internal Server Error although Token is created

I made an very simple Ajax in Laravel. I wanted to replace a message in the view after clicking on a button with a message that comes from the controller.

I get an 500 Internal Server Error, i searched and saw that token is often the reason for the error. I added one, but it is still not working. Anyone who had the problem before?

<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script>
    $(document).ready(function(){
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    })

    function getMessage(){
        console.log('test');
        $.ajax({
            type:'POST',
            url:'ajax',
            dataType:'text',
            success:function(data){
                $("#msg").html(data.msg);
            }
        });
    }
</script>

The Message that should be replaced and Button:

<div id = 'msg'>This message will be replaced using Ajax.
                Click the button to replace the message.</div>
            <button class="AjaxButton" onclick="getMessage()">Nachricht message</button>
        </div>

The Controller:

public function ajax(Request $request){
    console.log ('controller');
    $msg = "This is a simple message.";
    return response()->json('msg'->$msg);
}

The Route:

Route::post('/home/ajax','crudController@ajax');

enter image description here

Upvotes: 0

Views: 462

Answers (2)

ZeroOne
ZeroOne

Reputation: 9117

laravel comes with axios. axios already include csrf_token in ajax method..

axios.post("{{ route('your_route') }}")
.then(function (response) {
    $("#msg").html(response.data.msg);
})
.catch(function (error) {
    console.log(error);
});

edit

axios.post({{ route ('') }}, {
    firstName: 'Fred',
    lastName: 'Flintstone',
    address : 'Address example'
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});

Upvotes: 1

Black
Black

Reputation: 20212

console.log does not exist in PHP. Remove it and it should work.

Open your .env file and change APP_DEBUG to true (APP_DEBUG=true) To see more details about the errors. https://laravel.com/docs/5.5/errors


Also try to change your ajax request to this:

    $.ajax({
        type:'POST',
        url:'/home/ajax',
        data: '_token = <?php echo csrf_token() ?>',
        success: function(response){
            $("#msg").html(response.msg);
        }
    });

And in your Controller change your ajax function to this:

public function ajax(Request $request)
{
    $msg = "This is a simple message.";
    return response()->json(array('msg'=> $msg), 200);
}

There is something wrong with your Laravel setup, normally you should see an error message like this:

enter image description here

Upvotes: 0

Related Questions