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

jhyaps's avatar

Validation not recognizing AJAX-populated values in Laravel form submission

Hello everyone,

I'm encountering an issue with form validation in my Laravel application, specifically when submitting a MODAL FORM populated with data retrieved via AJAX. Despite successfully populating the form fields with values received from an AJAX request, the laravel request validation continues to treat these fields as empty or null, resulting in validation errors indicating that the fields are required.

Here's a brief overview of the scenario and the steps I've taken:

  1. I have a form for editing questions in my application.
  2. When a user clicks the "Edit" button for a question, an AJAX request fetches the question data from the server and populates the form fields with the retrieved values.
  3. The form includes various fields such as question text, options, correct answer, etc.
  4. Upon submitting the form, the data is sent via AJAX to the server for validation and processing. However, even though the form fields are populated with values from the AJAX response, the server-side validation does not recognize these values and treats the fields as required triggering validation errors.

My code works totally fine while storing in database via ajax but fails to submit in update. Currently , I am using one modal with the form and handle via ajax till now. Here's a simplified version of the JavaScript code handling the form submission:

$(document).ready(function() {
    $('#submitForm').click(function(e) {
        e.preventDefault();

        var formData = new FormData(document.getElementById("addQuestion"));
        var method = $('#id').val() ? 'PATCH' : 'POST';
        var url = $('#id').val() ? '{{ route('admin.questions.update', ['question' => ':question_id']) }}' : '{{ route('admin.questions.store') }}';
        url = url.replace(':question_id', $('#id').val());

        $('#submitForm').html('Please Wait...');
        $("#submitForm").attr("disabled", true);

        $.ajax({
            url: url,
            type: method,
            data: formData,
            processData: false,
            contentType: false,
            beforeSend: function() {
                $('span.error-text').text('');
            },
            success: function(data) {
                console.log(data);
                if (data.success) {
                    var setId = {{ $setId }};
                    window.location.href = "{{ route('admin.questions.index') }}?setid=" + setId;
                } else {
                    $('#submitForm').html('Save');
                    $("#submitForm").attr("disabled", false);
                    $('.is-invalid').removeClass('is-invalid');
                    $.each(data.error, function(key, value) {
                        $('#addQuestion').find('[name="' + key + '"]').addClass('is-invalid');
                        $('span.' + key.replace(/\./gi, "_") + '_error').append(value);
                    });
                }
            },
            error: function(data) {
                console.log(data);
            }
        });
    });
});

And here's how i am fetching the value from server in the form via ajax:

$(document).on('click', '.edit_modal', function() {
            var questionId = $(this).val();
            url = '{{ route('admin.questions.edit', ['question' => ':question_id']) }}';
            url = url.replace(':question_id', questionId);

            $.ajax({
                type: "GET",
                url: url,
                success: function(data) {
                    console.log(data);
                    $('#pattern_id').val(data.pattern_id);

                    $('#id').val(data.id);
                    $('#set_id').val(data.set_id);
                    $('#paper_id').val(data.paper_id);
                    $('#cols').val(data.cols);
                    $('#difficulty_level_id').val(data.difficulty_level_id);
                    $('#status_id').val(data.status_id);
                    $('#question').summernote('code', data.question);

                    $('#addQuestionModal').modal('show');
                },
                error: function(data) {
                    console.log('Error:', data);
                }
            });
        });

this is my current issue

Edit Form Modal

I've tried debugging the issue by inspecting the form data before submission and reviewing the server-side validation rules, but I haven't been able to identify the root cause of the problem.

Any insights or suggestions on how to troubleshoot and resolve this issue would be greatly appreciated. Thank you in advance for your help!

0 likes
10 replies
gych's avatar

If you console log formData before sending the post request, which value does it contain?

jhyaps's avatar

@gych

if i console.log to the formData i get this sort of result

{
    "id": 2,
    "set_id": 99,
    "paper_id": 1,
    "pattern_id": 1,
    "cols": 1,
    "question": "Option Values Not Updated: Ensure that the options within the select element are updated with the new values received from the AJAX request. If the options are not updated, the selected value may appear visually in the dropdown, but it may not be recognized as a valid value when the form is submitted.",
    "question_header": "Option Values Not Updated:",
    "a": null,
    "b": null,
    "c": null,
    "d": null,
    "correct_answer": "Opt",
    "remarks": "Ensure that the options within the select element are updated with the new values received from the AJAX request.",
    "difficulty_level_id": 1,
    "status_id": 1,
    "sort_order": null,
    "deleted_at": null,
    "created_at": "2024-02-22T15:47:20.000000Z",
    "updated_at": "2024-02-22T15:47:20.000000Z"
}

This value is the same value from the image i asked in the question .

jhyaps's avatar

@amitsolanki24_

Yes i have checked,

the value is showing in here

pattern_id: 1
cols: 1
difficulty_level_id: 1
status_id: 1
question:  Ensure that the options within the select element are updated with the new values received from the AJAX request. If the options are not updated, the selected value may appear visually in the dropdown, but it may not be recognized as a valid value when the form is submitted.
files: (binary)
a: 
b: 
c: 
d: 
question_header: Option Values Not Updated:
correct_answer: Opt
remarks: Ensure that the options within the select element are updated with the new values received from the AJAX request.
id: 2
set_id: 99
paper_id: 


But in preview section i am getting this error

{
  "error_from": "validation",
  "error": {
    "set_id": [
      "The set id field is required."
    ],
    "paper_id": [
      "The paper id field is required."
    ],
    "pattern_id": [
      "The pattern id field is required."
    ],
    "cols": [
      "The cols field is required."
    ],
    "question": [
      "The question field is required."
    ],
    "correct_answer": [
      "The correct answer field is required."
    ],
    "difficulty_level_id": [
      "The difficulty level id field is required."
    ],
    "status_id": [
      "The status id field is required."
    ]
  }
}

1 like
amitsolanki24_'s avatar

@jhyaps if you are using patch/put method than try to change into post.

Or may be need to check your request url.

gych's avatar
gych
Best Answer
Level 29

@jhyaps Does your validation work when its a POST request or does it not work with either post or patch?

If so you can try the code below, this will append the method PATCH to the formdata when #id has a value but always use axios post. Laravel should be able to recognize this.

$(document).ready(function() {
    $('#submitForm').click(function(e) {
        e.preventDefault();

        var formData = new FormData(document.getElementById("addQuestion"));
		if($('#id').val()) formData.append("_method", 'PATCH'); // append PATCH _method

        var url = $('#id').val() ? '{{ route('admin.questions.update', ['question' => ':question_id']) }}' : '{{ route('admin.questions.store') }}';
        url = url.replace(':question_id', $('#id').val());

        $('#submitForm').html('Please Wait...');
        $("#submitForm").attr("disabled", true);

        $.ajax({
            url: url,
            type: 'POST',
            data: formData,
			headers: {'Content-Type': 'multipart/form-data' },
            processData: false,
            contentType: false,
            beforeSend: function() {
                $('span.error-text').text('');
            },
            success: function(data) {
                console.log(data);
                if (data.success) {
                    var setId = {{ $setId }};
                    window.location.href = "{{ route('admin.questions.index') }}?setid=" + setId;
                } else {
                    $('#submitForm').html('Save');
                    $("#submitForm").attr("disabled", false);
                    $('.is-invalid').removeClass('is-invalid');
                    $.each(data.error, function(key, value) {
                        $('#addQuestion').find('[name="' + key + '"]').addClass('is-invalid');
                        $('span.' + key.replace(/\./gi, "_") + '_error').append(value);
                    });
                }
            },
            error: function(data) {
                console.log(data);
            }
        });
    });
});
1 like
jhyaps's avatar

@gych Actually, it works perfectly fine in the POST Request, but in case of patch, even i have value attached through ajax (see the code above), Shows validation error (see the image above). even i check with my formdata, there is value, but cannot update the post because of validtion.

jhyaps's avatar

@gych Thank you soo much for your help, You save my day. I was stuck for almost a week in this

I only modified the some of the suggestion you give me. like I totally remove my method and add a method append to the formData if id has value.

and replace the type:method with type:'POST'

Here is my Full Code for anyone who needs

$(document).ready(function() {
            $('#submitForm').click(function(e) {

                e.preventDefault();

                $.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    }
                });

                var formData = new FormData(document.getElementById("addQuestion"));
                if($('#id').val()) formData.append("_method", 'PATCH'); // append PATCH _method changes
                // var method = $('#id').val() ? 'PATCH' : 'POST';
                var url = $('#id').val() ? '{{ route('admin.questions.update', ['question' => ':question_id']) }}' : '{{ route('admin.questions.store') }}';
                url = url.replace(':question_id', $('#id').val());

                $('#submitForm').html('Please Wait...');
                $("#submitForm").attr("disabled", true);

                $.ajax({
                    url: url,
                    type: 'POST', //changes
                    dataType: 'json',
                    data: formData,
                    contentType: false,
                    crossDomain: true,
                    processData: false,
                    cache: false,
                    beforeSend: function() {
                        $('span.error-text').text('');
                    },
                    success: function(data) {

                        if (data.success) {
                            // console.log(data);
                            var setId = {{ $setId }};
                            window.location.href = "{{ route('admin.questions.index') }}?setid=" + setId;
                        } else {

                            $('#submitForm').html('Save');
                            $("#submitForm").attr("disabled", false);

                            $('.is-invalid').removeClass('is-invalid');

                            $.each(data.error, function(key, value) {

                                $('#addQuestion').find('[name="' + key + '"]').addClass('is-invalid');

                                $('span.' + key.replace(/\./gi, "_") + '_error').append(value);

                            });
                        }
                    },
                    error: function(data) {
                        // console.log(data);
                    }
                });
            });

        });

````
3 likes
gych's avatar

@jhyaps Nice that it works now! :) I'm glad I could help

1 like

Please or to participate in this conversation.