Receive data select multiple serialize (); Jquery- Ajax

1

Always the following code to send and receive data from a form, first I group them in formData and then in php I take them out one by one to know their value, however I have several selects and only take the last value (or be the last element selected), does anyone know how I can know all the values in the php?

Jquery:

function savepar(idForm){
    var formData = $("#"+idForm).serialize();
    $.ajax({
                data: { data:formData },
                type: "POST",
                url: "include/q_setData.php",
                success: function(data) {
                    alert(data);
                }
             });
    return false;
}

PHP:

  parse_str($_POST['data'], $searcharray);
                foreach($searcharray as $nombre_campo => $valor){ 
                   $asignacion = "\$" . $nombre_campo . "='" . $valor . "';"; 
                       eval($asignacion);
                     echo $asignacion."  "."<br>";
                }
    
asked by Andress Blend 17.02.2017 в 20:07
source

1 answer

1

Good Andress Blend,

When you send a select multiple field using serialize, the result of the encoded url is similar to this

lista=1&lista=2&lista=3 

The html being the next one

<select name="lista" multiple> 
    <option selected value="1">1</option>
    <option selected  value="2">2</option>
    <option selected  value="3">3</option>
</select>

I should send something similar to this, or at least it is what we would like it to appear.

lista=[1,2,3]&otraVariable=valor

In order to get it try using JSON.Stringify in this way

<?php
  if($_POST)
   echo var_dump($_POST);
  else{
?>
<form id="formulario" action="javascript:savepar('formulario')">
   <select name="lista" multiple>
    <option value="1">1</option>
    <option value="2">2</option>
   </select>
   <input type="submit" value="Enviar" />
</form>
<div id="result"></div> 
<script >
function savepar(idForm) {
    var formData = $("#" + idForm).serialize(); 
    $.ajax({
        data: JSON.stringify(formData),
        type: "POST",
        url: "test.php",
        success: function (data) {
            $('#result').html(data)
        }
    });
    return false;
  }
</script>
<?php }?>

As you can see, you'll already have it in a list

In the additional information of the developer tools you can see the difference of how it is sent with stringify and without stringify.

With stringify

Without Stringify

That is to say really if it sends it, but with the same name and php it reselects the variable.

Greetings and I hope you have solved the doubt.

    
answered by 22.02.2017 в 22:15