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

trav1s's avatar

Laravel 9 AJAX Form Submitting with jQuery

/del

0 likes
6 replies
amit_kumar_biswas's avatar

First Thing to know is that error code 422 means Validation Error.

This error occurs due to no data sending with the request. please try this code

$("#form_create_account").submit(function(e) {
    e.preventDefault();
   
    let formData = new FormData(this);
    $.ajax({
        headers: {
            'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
        },
        url: $(this).attr('action'),
        type: $(this).attr('method'),
        data: formData,
        contentType: false,
        processData: false,
        beforeSend: function() {
            $('#createAccountBtn').html('Loading.....');
        },
        error: function(response) {
            let formErrors = response.responseJSON.errors;
            let htmlErrors = '<div class="invalid-feedback">';

            if(formErrors.hasOwnProperty('email')) {
                htmlErrors += formErrors.email[0];
            }
            if(formErrors.hasOwnProperty('password')) {
                htmlErrors += formErrors.password[0];
            }
            if(formErrors.hasOwnProperty('password_confirmation')) {
                htmlErrors += formErrors.password_confirmation[0];
            }
            if(formErrors.hasOwnProperty('cf-turnstile-response')) {
                htmlErrors += formErrors.cf-turnstile-response[0];
            }

            $('.invalid-feedback').html(htmlErrors);

        },
        success: function(response) {
            console.log(response);
            $('#createAccountBtn').html('Account is created!');
        },
    });

});
2 likes
tisuchi's avatar

@trav1s It appears that the error is occurring because the form data is not being properly passed to the server. One potential issue is that the contentType and processData options in the AJAX request are set to false. This tells jQuery not to process the data as a query string or JSON, but to send it as is. However, in your Laravel code, you are expecting the data to be in the request body as a standard form submission.

Try setting contentType to 'application/x-www-form-urlencoded' and processData to true. This will tell jQuery to process the data as a standard form submission, which should match the expectations of your server-side code.

$.ajax({
    headers: {
        'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
    },
    url: $(this).attr('action'),
    method: $(this).attr('method'),
    data: formData,
    contentType: 'application/x-www-form-urlencoded',
    processData: true,
    // ...
});

Also, you need to check that you are passing the right 'action' and 'method' in your jQuery ajax call. Make sure the route and method name is correct.

Additionally, it's also possible that the error is occurring because of CSRF protection in Laravel. Make sure you have the CSRF token included in your form and that it is being passed to the server in the headers of the AJAX request.

1 like
trav1s's avatar

@tisuchi thank you. I have already fixed that issue. But now i'm don't quite understand how to show errors on frontend using jQuery ((

Urvin's avatar

@trav1s Just Use the Core Javascript or Jquery Feature. Like If you want Display Message then Just create tag give the id or class name to that tag In Jquery side call append or set value method to set value to that particular tag class. Now you good to go :)

trav1s's avatar

Please tell me how to beautifully display errors for each input separately?

Now i'm using that code:

            error: function (jqXHR, exception) {
                if (jqXHR.status === 0) {
                    alert('Not connect. Verify Network.');
                } else if (jqXHR.status == 404) {
                    alert('Requested page not found (404).');
                } else if (jqXHR.status == 500) {
                    alert('Internal Server Error (500).');
                } else if (exception === 'parsererror') {
                    alert('Requested JSON parse failed.');
                } else if (exception === 'timeout') {
                    alert('Time out error.');
                } else if (exception === 'abort') {
                    alert('Ajax request aborted.');
                } else {
                    $(".invalid-feedback").append(JSON.stringify(jqXHR.responseText));
                }
            },

And it's works ,but it looks very bad to the user. How to fix it?

Urvin's avatar

@trav1s Try this

error: function (jqXHR, exception) { if (jqXHR.status === 0) { $("#errorMessage").html("'Not connect. Verify Network.'"); $("#errorMessage").css("color", "red"); } },

Please or to participate in this conversation.