0

I have a form that will often be changing. I try to find a solution for not editing the AJAX call each time there is a change in the form.

So for exemple:

FORM:

<form>
    <label>RED</label>
    <input type="text" id="RED"><br>
    <label>BLUE</label>
    <input type="text" id="BLUE"><br>
    <label>YELLOW</label>
    <input type="text" id="YELLOW"><br>
    <label>ORANGE</label>
    <input type="text" id="ORANGE"><br>
    <label>PINK</label>
    <input type="text" id="PINK"><br>
    <label>GREEN</label>
    <input type="text" id="GREEN"><br>

    <input type="submit" name="submit">
</form>

AJAX CALL:

<script type="text/javascript">

$(document).on("click", ".fiche_client--btn--actualiser", function(e){   
  e.preventDefault();

    // Informations Personnelles
    var RED = $('#RED').val();
    var BLUE = $('#BLUE').val();
    var YELLOW = $('#YELLOW').val();
    var ORANGE = $('#ORANGE').val();
    var PINK = $('#PINK').val();
    var GREEN = $('#GREEN').val();

  $.ajax({
    type:'POST',
    data:{
        RED:RED,
        BLUE:BLUE,
        YELLOW:YELLOW,
        ORANGE:ORANGE,
        PINK:PINK,
        GREEN:GREEN,
        },
    url:'/url/colors.php',
    success:function(data) {                
      if(data){
        alert('Pocket!');
      }else{
        alert('Update failed');
      }
    }
  });
});

</script>

I'm trying to automatise the process for:

1/ The AJAX's call understand how many <input> there are, put them automatically in var in the javascript and also automatically in data in the ajax part.

2/ The script called by the ajax (/url/color.php) obtains the result as an array like this [RED] => input's content [BLUE] => input's content [YELLOW] => input's content (and so on...)

Is it something doable or totally impossible in php?

1 Answers1

0

If I understand the question correctly, there is absolutely something for this in jQuery: it's called .serialize(). It will get all of the inputs in the form and create a query string out of them:

$(document).on("click", ".fiche_client--btn--actualiser", function(e){   
  e.preventDefault();

    // Informations Personnelles
    let data = $("form").serialize();

  $.ajax({
    type:'POST',
    data: data,
    url:'/url/colors.php',
    success:function(data) {                
      if(data){
        alert('Pocket!');
      }else{
        alert('Update failed');
      }
    }
  });
});
Yaakov Ainspan
  • 3,598
  • 3
  • 23
  • 45