Answer the question
In order to leave comments, you need to log in
How to correctly validate the entered data through ajax?
The site has a form with an unknown number of fields (there may be dozens of them).
I want to make a check so that when entering data in each field, the data is sent to the server via ajax and checked for existence in the database.
With one field, of course, we send a request, compare it with a certain field in the database and return the result.
And how to do (do) correctly when there are a lot of them? For each, create your own JS script that will send data and create your own function on the server for each?
Answer the question
In order to leave comments, you need to log in
for each field you can make a service attribute, for example, "data_type"
$('body').on('change', '.ajax_input', function () {
var data_type= $(this).attr('data_type'); // читаешь атрибут поля ввода
switch (data_type) {
case 'create_new_tag':
// здесь передаешь аяксом на сервер значение и action
//типа
$.ajax({
url: "application/check_data.php",
dataType: "json",
data: {
data_type: data_type, // это будет в данном случае create_new_tag
page_id: $('#new_tag').val(),
//бла бла бла...
Do you want to check for uniqueness on input?
and if there are many fields.. check before recording, if not all are unique, do not record and give an error which field is not unique. if there are not so many of them, then they usually make a request with a delay and then do whatever you want with the received data. if you want to highlight an error, if you want to create, if you want to check .. It all depends on what you need in the end
"Create your own JS script for each" - no, you just write the form data into an array, then send the array with Ajax, and sort through each array value for validity, then catch the ones that are not suitable and send back an error, or what you need.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question