简体   繁体   中英

How to send an Ajax request to Laravel 5.0 framework?

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)

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.

$.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');

    }

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM