If you console log formData before sending the post request, which value does it contain?
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:
- I have a form for editing questions in my application.
- 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.
- The form includes various fields such as question text, options, correct answer, etc.
- 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

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!
@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);
}
});
});
});
Please or to participate in this conversation.