[php] Ajax post request in laravel 5 return error 500 (Internal Server Error)

This is my test ajax in laravel 5 (refer below)

$("#try").click(function(){
    var url = $(this).attr("data-link");
    $.ajax({
        url: "test",
        type:"POST",
        data: { testdata : 'testdatacontent' },
        success:function(data){
            alert(data);
        },error:function(){ 
            alert("error!!!!");
        }
    }); //end of ajax
});

and the trigger link

<a href="#" id="try" data-link="{{ url('/test') }}">Try</a>

and my route

Route::post('test', function()
{
    return 'Success! ajax in laravel 5';
});

but it gives me an error when I run the console in google chrome and it doesn't return the expected response "return 'Success! ajax in laravel 5';"

POST http://juliver.laravel.com/test 500 (Internal Server Error)

whats wrong/problem to my code? anything I'm missing?

This question is related to php jquery ajax laravel laravel-5

The answer is


I guess this has been solved by now but still the best thing to do here is to send the token with your form

{!! csrf_field() !!}

and then in your ajax

$("#try").click(function(){
var url = $(this).attr("data-link");
$.ajax({
    url: "test",
    type:"POST",
    data: { '_token': token, 'someOtherData': someOtherData },
    success:function(data){
        alert(data);
    },error:function(){ 
        alert("error!!!!");
    }
}); //end of ajax
});

In App\Http\Middleware\VerifyCsrfToken.php you could try updating the file to something like:

class VerifyCsrfToken extends BaseVerifier {

    private $openRoutes =
    [
        ...excluded routes
    ];

    public function handle($request, Closure $next)
    {
        foreach($this->openRoutes as $route)
        {
            if ($request->is($route))
            {
                return $next($request);
            }
        }

        return parent::handle($request, $next);
    }
};

This allows you to explicitly bypass specific routes that you do not want verified without disabling csrf validation globally.


for me this error cause of different stuff. i have two ajax call in my page. first one for save comment and another one for save like. in my routes.php i had this:

Route::post('posts/show','PostController@save_comment');
Route::post('posts/show','PostController@save_like');

and i got 500 internal server error for my save like ajax call. so i change second line http request type to PUT and error goes away. you can use PATCH too. maybe it helps.


Using post jquery instead helped me to solve this problem

$.post('url', data, function(response) {
    console.log(response);
});

90% of the laravel ajax internal server error is due to missing CSRF token. other reasons can inlucde:

  • Wrong Request Type (e.g sending post to get)
  • Wrong data type recived (e.g ajax is expecting JSON and app returns string)
  • Your .htaccess is misconfigured
  • Missing Route
  • Code Error

You can read further about this in details here: https://abbasharoon.me/how-to-fix-laravel-ajax-500-internal-server-error/


Laravel 7.X In bootstrap.js, in axios related code, add:

window.axios.defaults.headers.common['X-CSRF-TOKEN'] = $('meta[name="csrf-token"]').attr('content');

Solved lot of unexplained 500 ajax errors. Of course it's for those who use axios


You can add your URLs to VerifyCsrfToken.php middleware. The URLs will be excluded from CSRF verification.

protected $except = [
    "your url",
    "your url/abc"
];

By default Laravel comes with CSRF middleware.

You have 2 options:

  1. Send token in you request
  2. Disable CSRF middleware (not recomended): in app\Http\Kernel.php remove VerifyCsrfToken from $middleware array

you have to pass the csrf field through ajax please look at the code here

$.ajax({
                                        type: "POST",
                                        url:'{{URL::to("/delete-specialist")}}',
                                        data: {
                                            id: id,

                                            _token: $('#signup-token').val()
                                        },
                                        datatype: 'html',
                                        success: function (response) {
                                            if(response=="deleted"){
                                                $("#"+id).hide();
                                                $("#message").html("successfully deleted");
                                            }

                                        }

                                    });

and you also need to write this input field before this

<input id="signup-token" name="_token" type="hidden" value="{{csrf_token()}}">

still if you do not understand please enjoy this video https://www.youtube.com/watch?v=ykXL8o0slJA&t=20s


Short and Simple Solution

e.preventDefault();
var value = $('#id').val();
var id = $('#some_id').val();
url="{{url('office/service/requirement/rule_delete/')}}" +"/"+ id;
console.log(url);
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});
$.ajax({
/* the route pointing to the post function */
    url: url,
    type: 'DELETE',
/* send the csrf-token and the input to the controller */
    data: {message:value},
    dataType: 'JSON',
/* remind that 'data' is the response of the AjaxController */
    success: function (data) { 
    console.log(data)
    //$('.writeinfo').append(data.msg);
    //$('#ruleRow'+id).remove();
    }
});
return false;

do not forget add "use Illuminate\Http\Request;" on your controller


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to laravel

Parameter binding on left joins with array in Laravel Query Builder Laravel 4 with Sentry 2 add user to a group on Registration Target class controller does not exist - Laravel 8 Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue? Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required How can I run specific migration in laravel Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

Examples related to laravel-5

Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory Can't install laravel installer via composer Including a css file in a blade template? No Application Encryption Key Has Been Specified How to Install Font Awesome in Laravel Mix Laravel Migration Error: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes Laravel 5.4 redirection to custom url after login How to set the default value of an attribute on a Laravel model laravel 5.3 new Auth::routes()