How to send an Ajax request to Laravel 5.0 framewo

2019-05-21 02:18发布

问题:

I've tried to fix this all morning and I can't seem to find any working method online.

I'm trying to do a simple ajax request to my Laravel controller and get the data it sends. I've simplified it to the maximum and I still get ERROR 500 with data "undefined".

It seems that every examples onlines are about Laravel 4.0, I'm not sure if they changed something or not but none seem to work. I also tried changing the route to "any" and it works on the direct access but not with the ajax request.

Thanks.

Controller :

<?php namespace App\Http\Controllers;
use Session, DB, Request;
class AjaxController extends Controller {

    public function question()
    {
        print_r("Made It");
        die();
    }
}

Route :

Route::post('/ajax/question', 'AjaxController@question');

Javascript :

$.ajax({
    url: "/ajax/question",
    method: 'POST',
    data:  { 'answered': '1' },
    processData: false,
    contentType: false,
    cache: false,
    success: function(data) {
        console.log(data);
        console.log("success");
    },
    error: function(data) {  
        console.log(data);
        console.log("error");                 
    }
});

console.log(data) gives the following :

readyState

    4
responseText

    ""
status

    500
statusText

    "Internal Server Error"
abort

    function(e)
always

    function()
complete

    function()
done

    function()
error

    function()
fail

    function()
getAllResponseHeaders

    function()
getResponseHeader

    function(e)
overrideMimeType

    function(e)
pipe

    function()
progress

    function()
promise

    function(e)
setRequestHeader

    function(e, t)
state

    function()
statusCode

    function(e)
success

    function()
then

    function()

EDIT : If I change the request to GET it works properly. (Set route to any)

回答1:

If you look in your browser console at the response, chances are you're hitting the CSRF middleware. You need to post _token with the current value for the user's csrf_token().

We include this in our page layouts in order to automatically add it to all AJAX requests via a header (which Laravel understands):

<script>
$(function() {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': {!! json_encode(csrf_token()) !!};,
        }
    });
});
</script>

See https://github.com/laravel/framework/blob/8687d42c6674e47efc093b5092ea217b62ba293a/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php#L55 for details on how that works.



回答2:

$.ajax({

    type: "POST",

    URL: "test/",

    data: { 

        id: $(this).val(), // < note use of 'this' here

        access_token: $("#access_token").val() 
    },

    success: function(result) {

        alert('YES');
    },
    error: function(result) {

        alert('Some Thing went wrong');

    }

});