PHP - problema al cargar valor en campo selectpicker

 
Vista:
sin imagen de perfil
Val: 27
Ha aumentado su posición en 4 puestos en PHP (en relación al último mes)
Gráfica de PHP

problema al cargar valor en campo selectpicker

Publicado por Endika (14 intervenciones) el 30/08/2017 08:58:09
Hola¡ He implementado con éxito en mi formulario de clientes dos selectpicker dependientes, provincias y municipios. Los valores de municipios cambian cada vez que el usuario hace click en una provincia.

Ahora me encuentro con un problema.

Cada vez que le doy al botón editar cliente, me carga en el formulario correspondiente todos los datos del cliente menos el municipio que tiene asignado. He chequeado que la variable tenga un valor y sí que lo tiene, así que el problema se que está en que no se carga el valor en el selectpicker.

Supongo que me faltará algo de código o hacer algún refresh más en algún momento ¿Podéis echarme una mano?

código:

1) El formulario + JS con evento on change asociado a provincia

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
<!-- Esta es la vista HTML + un pequeño JS con el que quiero enviar los datos por AJAX-->
<?php
//Activamos el almacenamiento en el buffer
ob_start();
session_start();
 
if (!isset($_SESSION["nombre"]))
{
  header("Location: login.html");
}
else
{
require 'header.php';
if ($_SESSION['gestion']==1)
{
?>
<!--Contenido-->
      <!-- Content Wrapper. Contains page content -->
      <div class="content-wrapper">
        <!-- Main content -->
        <section class="content">
            <div class="row">
              <div class="col-md-12">
                  <div class="box">
                    <div class="box-header with-border">
                          <h1 class="box-title">Clientes <button class="btn btn-success" id="btnagregar" onclick="mostrarform(true)"><i class="fa fa-plus-circle"></i> Agregar</button></h1>
                        <div class="box-tools pull-right">
                        </div>
                    </div>
                    <!-- /.box-header -->
                    <!-- centro -->
                    <div class="panel-body table-responsive" id="listadoregistros">
                        <table id="tbllistado" class="table table-striped table-bordered table-condensed table-hover">
                          <thead>
							<th>Opciones</th>
							<th>Forma de pago</th>
							<th>Provincia</th>
							<th>Municipio</th>
                            <th>T.L. Fiscal</th>
                            <th>Nombre comercial</th>
                            <th>Zona</th>
                            <th>Teléfono</th>
                            <th>Móvil</th>
                            <th>Fax</th>
							<th>Contacto</th>
							<th>Domicilio 1</th>
							<th>Domicilio 2</th>
                            <th>Población</th>
                            <th>C.P</th>
                            <th>NIF/CIF</th>
                            <th>Representante</th>
                            <th>CCC</th>
							<th>IBAN</th>
							<th>Recargo Equivalencia (S/N)</th>
							<th>Descuento comercial</th>
							<th>Descuento pronto pago</th>
							<th>Financiación</th>
                          </thead>
                          <tbody>
                          </tbody>
                          <tfoot>
							<th>Opciones</th>
							<th>Forma de pago</th>
							<th>Provincia</th>
							<th>Municipio</th>
                            <th>T.L. Fiscal</th>
                            <th>Nombre comercial</th>
                            <th>Zona</th>
                            <th>Teléfono</th>
                            <th>Móvil</th>
                            <th>Fax</th>
							<th>Contacto</th>
							<th>Domicilio 1</th>
							<th>Domicilio 2</th>
                            <th>Población</th>
                            <th>C.P</th>
                            <th>NIF/CIF</th>
                            <th>Representante</th>
							<th>CCC</th>
							<th>IBAN</th>
							<th>Recargo Equivalencia (S/N)</th>
							<th>Descuento comercial</th>
							<th>Descuento pronto pago</th>
							<th>Financiación</th>
                          </tfoot>
                        </table>
                    </div>
                    <div class="panel-body" style="height: 1000px;" id="formularioregistros">
                        <form name="formulario" id="formulario" method="POST">
                          <div class="form-group col-lg-6 col-md-6 col-sm-6 col-xs-12">
                            <label>T.L Fiscal:</label>
                            <input type="hidden" name="idcliente" id="idcliente">
                            <input type="text" class="form-control" name="tlfiscal" id="tlfiscal" maxlength="30" placeholder="Razón social de la empresa" required>
                          </div>
                          <div class="form-group col-lg-6 col-md-6 col-sm-6 col-xs-12">
                            <label>Nombre:</label>
							<input type="text" class="form-control" name="nombre" id="nombre" maxlength="30" placeholder="Nombre comercial de la empresa">
                          </div>
 
						<div class="form-group col-lg-6 col-md-6 col-sm-6 col-xs-12">
                            <label>Provincia:</label>
                            <select id="idprovincia" name="idprovincia" class="form-control selectpicker" data-live-search="true" required>
							<option value="">Selecciona la provincia del cliente</option>
							</select>
                          </div>
						<div class="form-group col-lg-6 col-md-6 col-sm-6 col-xs-12">
                            <label>Municipio:</label>
                            <select id="idmunicipio" name="idmunicipio" class="form-control selectpicker" data-live-search="true" required>
							</select>
                          </div>
						  <div class="form-group col-lg-6 col-md-6 col-sm-6 col-xs-12">
                            etc
                          <div class="form-group col-lg-12 col-md-12 col-sm-12 col-xs-12">
                            <button class="btn btn-primary" type="submit" id="btnGuardar"><i class="fa fa-save"></i> Guardar</button>
 
                            <button class="btn btn-danger" onclick="cancelarform()" type="button"><i class="fa fa-arrow-circle-left"></i> Cancelar</button>
                          </div>
                        </form>
                    </div>
                    <!--Fin centro -->
                  </div><!-- /.box -->
              </div><!-- /.col -->
          </div><!-- /.row -->
      </section><!-- /.content -->
 
    </div><!-- /.content-wrapper -->
  <!--Fin-Contenido-->
<?php
}
else
{
  require 'noacceso.php';
}
require 'footer.php';
?>
<script type="text/javascript" src="scripts/clienteok.js"></script>
<script type="text/javascript">
$(document).ready(function(){
 
			$('#idprovincia').change(function(data){
				data.preventDefault();
 
				var provinciaID = $(this).val();
				var data = {'provinciaID': provinciaID};
 
				$.ajax({
					type:'POST',
					url:'../ajax/clientes.php?op=selectMunicipio',
					data: data,
					contentType: "application/x-www-form-urlencoded",
					success: function(data){
					$("#idmunicipio").html(data);
					$('#idmunicipio').selectpicker('refresh');
					}
				});
			});
});
 
 
 
</script>
<?php
}
ob_end_flush();
?>

2) PHP que gestiona qué quiere hacer el usuario mediante cases

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
<?php
require_once "../modelos/Cliente.php";
 
//creamos nuevo objeto entidad Cliente
$Cliente=new Cliente();
 
 
//limpiamos los valores del formulario
$idpago=isset($_POST["idpago"])? limpiarCadena($_POST["idpago"]):"";
$idmunicipio=isset($_POST["idmunicipio"])? limpiarCadena($_POST["idmunicipio"]):"";
$idprovincia=isset($_POST["idprovincia"])? limpiarCadena($_POST["idprovincia"]):"";
$idcliente=isset($_POST["idcliente"])? limpiarCadena($_POST["idcliente"]):"";
$tlfiscal=isset($_POST["tlfiscal"])? limpiarCadena($_POST["tlfiscal"]):"";
 
etc
 
 
switch ($_GET["op"]){
	case 'guardaryeditar':
 
		if (empty($idcliente)){
			$rspta=$Cliente->insertar($idpago,$idprovincia,$idmunicipio,$tlfiscal,$nombre,$zona,$telefono,$movil,$fax,$contacto,$domicilio1,$domicilio2,$poblacion,$cp,$idfiscal,$representante,$ccc,$iban,$bic,$re,$precioaplicable,$diaspago,$dtocomercial,$dtoppago,$financiacion);
			echo $rspta ? "Cliente registrado" : "Cliente no se pudo registrar";
		}
		else {
			$rspta=$Cliente->editar($idcliente,$idpago,$idprovincia,$idmunicipio,$tlfiscal,$nombre,$zona,$telefono,$movil,$fax,$contacto,$domicilio1,$domicilio2,$poblacion,$cp,$idfiscal,$representante,$ccc,$iban,$bic,$re,$precioaplicable,$diaspago,$dtocomercial,$dtoppago,$financiacion);
			echo $rspta ? "Cliente actualizado" : "Cliente no se pudo actualizar";
		}
	break;
 
	case 'eliminar':
		$rspta=$Cliente->eliminar($idcliente);
 		echo $rspta ? "Cliente eliminado" : "Cliente no se puede eliminar";
	break;
 
	case 'mostrar':
		$rspta=$Cliente->mostrar($idcliente);
 		//Codificar el resultado utilizando json
 		echo json_encode($rspta);
	break;
 
	case 'listar':
		$rspta=$Cliente->listar();
 		//Vamos a declarar un array
 		$data= Array();
 
 		while ($reg=$rspta->fetch_object()){
 			$data[]=array(
			//en la primera posición del array leemos los ID que es la primary key, y además pintamos los botoncitos de eliminar y editar. El resto carga en el array los otros campos de la tabla :)
 				"0"=>'<button class="btn btn-warning" onclick="mostrar('.$reg->idcliente.')"><i class="fa fa-pencil"></i></button>'.
 					' <button class="btn btn-danger" onclick="eliminar('.$reg->idcliente.')"><i class="fa fa-trash"></i></button>',
 				"1"=>$reg->formapago,
 				"2"=>$reg->provincia,
 				"3"=>$reg->municipio,
				"4"=>$reg->tlfiscal,
 				"5"=>$reg->nombre,
				"6"=>$reg->zona,
 				"7"=>$reg->telefono,
				"8"=>$reg->movil,
				"9"=>$reg->fax,
				"10"=>$reg->contacto,
				"11"=>$reg->domicilio1,
				"12"=>$reg->domicilio2,
				"13"=>$reg->poblacion,
				"14"=>$reg->cp,
				"15"=>$reg->idfiscal,
 				"16"=>$reg->representante,
 				"17"=>$reg->ccc,
				"18"=>$reg->iban,
				"19"=>$reg->bic,
				"20"=>$reg->re,
				"21"=>$reg->precioaplicable,
				"22"=>$reg->diaspago,
				"23"=>$reg->dtocomercial,
				"24"=>$reg->dtoppago,
				"25"=>$reg->financiacion
 
 				);
 		}
 		$results = array(
 			"sEcho"=>1, //Información para el datatables
 			"iTotalRecords"=>count($data), //enviamos el total registros al datatable
 			"iTotalDisplayRecords"=>count($data), //enviamos el total registros a visualizar
 			"aaData"=>$data);
 		echo json_encode($results);
 
	break;
 
 
	//leemos todos los datos de la tabla formaspago para pintarlas como options en el select
	case "selectPago":
		require_once "../modelos/Formaspago.php";
		$fpago = new Formapago();
 
		$rspta = $fpago->select();
 
		while ($reg = $rspta->fetch_object())
				{
					echo '<option value=' . $reg->idpago . '>' . $reg->nombre . '</option>';
				}
	break;
 
	case "selectProvincia":
		require_once "../modelos/Provincias.php";
		$provincia = new Provincia();
 
		$rspta = $provincia->select();
 
		while ($reg = $rspta->fetch_object())
				{
					echo '<option value=' . $reg->id . '>' . $reg->provincia . '</option>';
				}
	break;
 
	case "selectMunicipio":
 
		require_once "../modelos/Municipios.php";
 
		$municipio = new Municipio();
 
		$provinciaID=$_POST['provinciaID'];
 
 
		$rspta = $municipio->select($provinciaID);
 
		while ($reg = $rspta->fetch_object())
				{
					echo '<option value=' . $reg->id . '>' . $reg->municipio . '</option>';
 
				}
 
		break;
}
 
?>

3) Fichero JS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
var tabla;
 
//Función que se ejecuta al inicio
function init(){
	mostrarform(false);
	listar();
 
	$("#formulario").on("submit",function(e)
	{
		guardaryeditar(e);
	});
 
	$.post("../ajax/clientes.php?op=selectPago", function(r){
	            $("#idpago").html(r);
	            $('#idpago').selectpicker('refresh');
 
	});
 
	$.post("../ajax/clientes.php?op=selectProvincia", function(r){
	            $("#idprovincia").html(r);
	            $('#idprovincia').selectpicker('refresh');
 
	});
 
 
	$.post("../ajax/clientes.php?op=selectMunicipio", function(r){
	            $("#idmunicipio").html(r);
	            $('#idmunicipio').selectpicker('refresh');
 
	});
 
 
}
 
function limpiar()
{
	$("#idcliente").val("");
	$("#idpago").val("");
	$("#idprovincia").val("");
	$("#idprovincia").selectpicker('refresh');
	$("#idmunicipio").val("");
	$("#idmunicipio").selectpicker('refresh');
	$("#tlfiscal").val("");
	$("#nombre").val("");
	$("#zona").val("");
	etc
}
 
function mostrarform(flag)
{
	limpiar();
	if (flag)
	{
		$("#listadoregistros").hide();
		$("#formularioregistros").show();
		$("#btnGuardar").prop("disabled",false);
		$("#btnagregar").hide();
	}
	else
	{
		$("#listadoregistros").show();
		$("#formularioregistros").hide();
		$("#btnagregar").show();
	}
}
 
 
function cancelarform()
{
	limpiar();
	mostrarform(false);
}
 
 
function listar()
{
	tabla=$('#tbllistado').dataTable(
	{
		"aProcessing": true,
	    "aServerSide": true,
	    dom: 'Bfrtip',
	    buttons: [
		            'copyHtml5',
		            'excelHtml5',
		            'csvHtml5',
		            'pdf'
		        ],
		"ajax":
				{
					url: '../ajax/clientes.php?op=listar',
					type : "get",
					dataType : "json",
					error: function(e){
						console.log(e.responseText);
					}
				},
		"bDestroy": true,
		"iDisplayLength":
	    "order": [[ 0, "desc" ]]
	}).DataTable();
}
//Función para guardar o editar
 
function guardaryeditar(e)
{
	e.preventDefault(); //No se activará la acción predeterminada del evento
	$("#btnGuardar").prop("disabled",true);
	var formData = new FormData($("#formulario")[0]);
 
	$.ajax({
		url: "../ajax/clientes.php?op=guardaryeditar",
	    type: "POST",
	    data: formData,
	    contentType: false,
	    processData: false,
 
	    success: function(datos)
	    {
	          bootbox.alert(datos);
	          mostrarform(false);
	          tabla.ajax.reload();
	    }
 
	});
	limpiar();
}
 
function mostrar(idcliente)
{
	$.post("../ajax/clientes.php?op=mostrar",{idcliente : idcliente}, function(data, status)
	{
		data = JSON.parse(data);
		mostrarform(true);
		$("#idpago").val(data.idpago);
		$('#idpago').selectpicker('refresh');
		$("#idprovincia").val(data.idprovincia);
		$('#idprovincia').selectpicker('refresh');
		$("#idmunicipio").val(data.idmunicipio);
		$('#idmunicipio').selectpicker('refresh');
		$("#idcliente").val(data.idcliente);
		$("#tlfiscal").val(data.tlfiscal);
		etc
 
 	})
}
 
 
function eliminar(idcliente)
{
	bootbox.confirm("¿Está Seguro de eliminar el cliente?", function(result){
		if(result)
        {
        	$.post("../ajax/clientes.php?op=eliminar", {idcliente : idcliente}, function(e){
        		bootbox.alert(e);
	            tabla.ajax.reload();
        	});
        }
	})
}
 
 
init();
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder