Search code examples
jqueryajaxlaraveltokenform-data

Laravel post request using ajax fails with "Symfony\Component\HttpKernel\Exception\HttpException"


        $("#login-form").submit(function(event) {
            event.preventDefault();
            $.ajax({
                type: "POST",
                url: "login",
                data: new FormData($(this)[0]),
                processData: false,
                success: function() {
                    alert(0);
                },
                error: function() {
                    alert(1);
                }
            });
        });

That's my code, and this is the error: Symfony\Component\HttpKernel\Exception\HttpException.

I tried to store new FormData($(this)[0]) in a variable and do myVar.get("_token") and it gets returned fine.

Solutions found until now by research are related to the token, but I don't think this is my case.


Solution

  • @Popescu Flaviu when you are the ajax for form submit in Laravel you have to use CSRF Token. you can use in form and get into your script for sending the request.

    headers: {'X-CSRF-TOKEN': $('input[name=_token]').val()}
    

    you have to use this in the header in your Ajax request. thank you. this will definitely help you.