I have a form select multiple
that is filled depending on the data of others select
, the case is that I want to send it ajax
to a file php
to make a communication with the database, the case is that I use the form to take the data $("#").serialize()
, so I don't know how to receive the data by php
, if someone can help me, I appreciate it.
JQuery Ajax
function enviarRegistro(){
if(validarCampos()){
var datos = $("#formRegistro").serialize();
$("#pageLoader").fadeIn("fast");
if($("#checkinput").prop("checked")){
$.ajax({
data: datos,
url: '/Jomar/users_control/controller/ControlAsisController.php?action=guardarHasta',
type: 'post',
success: function (response){
var html;
if(response.trim() != "1"){
html = "<h4> No se han podido insertar "+ response.trim() +" registros</h4>";
$("#respuesta").addClass("alert-danger");
$("#respuesta").html(html);
$("#pageLoader").fadeOut("fast");
$("#respuesta").fadeIn("slow");
setTimeout(function(){
$("#respuesta").fadeOut(2000, function() {
$("#respuesta").html("");
$("#respuesta").removeClass("alert-danger");
});
}, 2000);
}else{
$("#respuesta").addClass("alert-success");
html = "<h4> Se ha insertado correctamente </h4>";
$("#respuesta").html(html);
$("#pageLoader").fadeOut("fast");
$("#respuesta").fadeIn("slow");
$("#empleado").val(0);
$("#nota").val("");
llenarEmpleados();
$("#errores").fadeOut("slow");
setTimeout(function(){
$("#respuesta").removeClass("alert-success");
$("#respuesta").fadeOut(2000, function() {
$("#respuesta").html("");
});
}, 2000);
}
}
});
HTML
<select class="selectpicker" multiple data-size="6" data-live-search="true" id="empleado" name="empleado" disabled="disabled">
<option value="0" disabled>Seleccionar empleado</option>
</select>
Note that the JQuery function
serialize()
returns a thatstring
looks similar to a string passed byget
in the URL . Example:This string is not a JSON so the
type
one you have defined in the AJAX call is not the correct one. In addition to the fact that JSON is not a format that works for us in our case, since we have multiple fields like itkey
and this does not allow us to have it.That is why I suggest you use the function
serializeArray()
instead ofserialize()
.Example of converting select multiple to array:
Example of AJAX send call using the array obtained by serializeArray()
Then from PHP the only thing you would have to do is retrieve
$_POST
the sent data:To collect the multiple values of a select you need to send the
array
selected data using the name of the form field.Simply the name of the field will be
empleado[]
.