Send form inside a while with java, ajax php

Issue

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

Solution

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 the form supplied as the single argument. The FormData 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.

document.querySelectorAll('[type="submit"]').forEach(input => input.addEventListener('click',e=>{
  e.preventDefault();
  /*
    The `submit` button raised the event so the `event.target` refers to that button.
    From the button we know the `form` is the parentNode - but you can use `closest`
    to find the parent form.
  */
  let fd = new FormData( e.target.parentNode );
  
  fetch( 'accion.php', { method:'post', body:fd })
    .then(r=>r.text())
    .then(data=>{
      console.log(data);
      
      // call your success function.
      toastr.success('añadidas!', 'Actualización ', {
        "hideDuration": 1500
      });
    });
}))
<form data-id='msg-form-nota'>
  <input type='hidden' name='id_nota' value='123' />
  <label>
        Calificación obtenida:
        <input type='text' name='nota' class='form-control form-control-sm' value='Geronimo' placeholder='Introducir calificación' />
    </label>
  <input type='submit' class='btn btn-success btn-sm' value='Añadir/modificar calificación' />
</form>

<form data-id='msg-form-nota'>
  <input type='hidden' name='id_nota' value='456' />
  <label>
        Calificación obtenida:
        <input type='text' name='nota' class='form-control form-control-sm' value='Fred Flintsone' placeholder='Introducir calificación' />
    </label>
  <input type='submit' class='btn btn-success btn-sm' value='Añadir/modificar calificación' />
</form>

<form data-id='msg-form-nota'>
  <input type='hidden' name='id_nota' value='789' />
  <label>
        Calificación obtenida:
        <input type='text' name='nota' class='form-control form-control-sm' value='Spitfire' placeholder='Introducir calificación' />
    </label>
  <input type='submit' class='btn btn-success btn-sm' value='Añadir/modificar calificación' />
</form>

In the PHP script accion.php there will be 2 POST parameters sent by the fetch request. These two parameters have the same names as the form input elements. For instance:-

<?php

    #accion.php
    
    if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
        $_POST['id_nota'],
        $_POST['nota']
    )){
        // ... etc do whatever
    }
?>

Answered By – Professor Abronsius

Answer Checked By – Candace Johnson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.