I have the following html code with a form
<form id="msg-form-nota">
<input type="hidden" name="id_nota" id="id_nota" value="${project.id}">
<label for="textfield">Calificación obtenida:</label>
<input type="text" name="nota" id="nota" class="form-control form-control-sm" value="${project.nota}" placeholder="Introducir calificación"><br>
<input type="submit" name="submit" id="submit" class="btn btn-success btn-sm" value="Añadir/modificar calificación">
</form>
and then I use the following javascript/ajax code to manage the form
$('#msg-form-nota').submit(e => {
e.preventDefault();
const postData = {
nota: $('#nota').val(),
id: $('#id_nota').val()
};
const url ='accion.php';
$.post(url, postData, (response) => {
toastr.success('añadidas!', 'Actualización ', {"hideDuration": 1500});
});
});
The problem that I detect and I don’t know how to solve is that, for example, when using a while, 5 forms are created with the same name id, if I use the first form that loads me it works without problem, but if I use the rest, the form does not It works if not that all the content of the form goes to the url as if the method were a get, what can I do? Thank you
2
Answers
The issue, as your question implies, is because you’re repeating the same
id
attribute multiple times as the HTML is generated in a loop.The best way to fix this is to use common
class
attributes on the elements instead. Then you can target the specific instance which from thetarget
property of the event which is raised and passed as an argument to the event handler function. You can also use DOM traversal methods to find the related elements and retrieve their values.Also note that I wrapped the
input
within thelabel
element. This removes the need for thefor
andid
attributes on those elements, but retains the same functionality.If you wanted to completely remove the ID attributes from your forms/elements you can quite easily simplify the entire code by using a
FormData
object with a reference to theform
supplied as the single argument. TheFormData
object would collate the various input elements for use in the ajax request – thus negating the need to even try to identify the individual input elements explicitly.In the PHP script
accion.php
there will be 2 POST parameters sent by thefetch
request. These two parameters have the same names as the form input elements. For instance:-