Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

AlexanderKim's avatar

Ajax post request causes 500 internal server error

In short: 500 internal server error when trying to do a POST request using ajax to a resource controller's method.

Resource CurrencyController:

public function ajaxDeleteImage() {
    if ($request->isMethod('ajax')) {
        $path = $request->input('imgUrl');
        $id = $request->input('id');

        $currency = Currency::findOrFail($id);
        $currency->cur_icon = '';
        $currency->save();
        Storage::delete($path);

        return 'Deleted image!';
    }

    return App::abort(404);
}

Here's my routes:

/**
 * ajax requests
 */

Route::any('ajax-delete-image-currency', 'CurrencyController@ajaxDeleteImage');

/**
 * admin prefix
 */

Route::group(['prefix' => 'admin', 'middleware' => 'auth'], function() {
    Route::resource('request', 'ReqController');
    Route::resource('currency', 'CurrencyController');
});

edit.blade.php - where i created a form with multipart/form-data:

here are some form html code...

@section('custom_scripts')
<script type="text/javascript">
(function($) {

    var thisUrl = $('input[name="image-hidden"]').val();
    var currencyId = $('input[name=id]').val();

    // console.log(thisUrl);

    $('.del-image').click(function() {
        $.ajax({
            method: 'post',
            url: '/ajax-delete-image-currency',
            data: {imgUrl: thisUrl, id: currencyId},
            success: function(data) {
                console.log("removed image");
                window.location.reload();
            },
            error: function(e) {
                alert('Error' + e);
            }
        });
    });

})(jQuery);
</script>
@endsection

The problem is - i am getting internal server error 500 whenever i press on a button with class .del-image (sending post request with ajax).

Also i tried to delete whole method ajaxDeleteImage from a controller at all. Nothing happened, same 500 error. Seems like post request cannot reach that method in a CurrencyController.

Maybe i have a problem in my routes? Wrong sorting? I read that i have to move certain methods above resource controllers, so it would work correctly, but that it's not my case.

Please advice something.

0 likes
18 replies
zachleigh's avatar

Open up browser dev tools. Click the button to cause the error and go to the network tab. Click on the error respose to see the error received from Laravel.

1 like
zachleigh's avatar

Click on it. It should open up the response.

1 like
AlexanderKim's avatar

TokenMismatchException in VerifyCsrfToken.php line 67

zachleigh's avatar

You need to send the csrf token with your ajax request.

AlexanderKim's avatar
    var thisUrl = $('input[name="image-hidden"]').val();
    var currencyId = $('input[name=id]').val();
    var token = $('input[name=_token]').val();

    // console.log(thisUrl);

    $('.del-image').click(function() {
        $.ajax({
            method: 'post',
            url: '/ajax-delete-image-currency',
            data: {imgUrl: thisUrl, id: currencyId, tok: token},
            success: function(data) {
                console.log("removed image");
                window.location.reload();
            },
            error: function(e) {
                alert('Error' + e);
            }
        });
    });

but how to accept that token in a controller?

diaglyph's avatar

You should have something like:

$.ajaxSetup({ headers: { 'csrftoken' : '{{ csrf_token() }}' } });
AlexanderKim's avatar

How to adopt this code to my case? :) Could you help?

zachleigh's avatar
Level 47

Try this:

data: {imgUrl: thisUrl, id: currencyId, _token: token}
zachleigh's avatar

What does your form look like? If you dump the value of tokento the console, what do you see?

AlexanderKim's avatar
<form class="form-horizontal" role="form" method="POST" enctype="multipart/form-data" action="{{ url('/admin/currency/' . $currency->id) }}">
{{ csrf_field() }}
<input name="_method" type="hidden" value="PUT">
<input type="hidden" name="id" value="{{ $currency->id }}">
@if ($currency->cur_icon)
<input type="hidden" name="image-hidden" value="/uploads/{{ $currency->cur_icon }}">
@endif

<div class="form-group{{ $errors->has('cur_name') ? ' has-error' : '' }}">
<label for="cur_name" class="col-md-3 control-label">Curname</label>

<div class="col-md-9">
<input id="cur_name" type="text" class="form-control" name="cur_name" value="{{ $currency->cur_name }}">

                        @if ($errors->has('cur_name'))
                            <span class="help-block">
                                <strong>{{ $errors->first('cur_name') }}</strong>
                            </span>
                        @endif
                    </div>
                </div>

                

                <div class="form-group">
                    <div class="col-md-9 col-md-offset-3">
                        <button type="submit" class="btn btn-primary">
                            Save
                        </button>
                    </div>
                </div>
            </form>

zachleigh's avatar

After making the token change, are you still getting the same error?

AlexanderKim's avatar

After adding _token to ajax request i have the same error.

AlexanderKim's avatar

Sorry, now i am getting undefined variable $request. Why it doesn't work?

UPDATE. When i watch post request in Postman, it shows token mismatch error, but when i do GET request i'm getting undefined variable $request error. What the hell is going on :D

lindstrom's avatar

Try serializing the form data. Much simpler:

$('.del-image').click(function() {
    var form = $(this).closest('form');
    $.ajax({
        type: 'POST',
        url: form.prop('action'),
        data: form.serialize(),
        success: function(data) {
            console.log("removed image");
            window.location.reload();
        },
        error: function(e) {
            alert('Error' + e);
        }
     });
});
bencavens's avatar

This could happen if the server outputs the response too early. Can you check if you don't have an unwanted space or linebreak before your starting <?php tag.

Please or to participate in this conversation.