1

buenas noches tengo el siguiente script :

    $(document).ready(function() {

         $.ajax({
             dataType: "json",
             data: [],
             url: "https://ubicaciones.paginasweb.cr/provincias.json",
            type: 'GET',
             crossDomain: true,
             success: function(data) {
                 agregarProvincias(data);
             }
         });


    $(document).on('change', '#provincia > select', function() {
        var provincia = this.value;
         $.ajax({
             dataType: "json",
             url: "https://ubicaciones.paginasweb.cr/provincia/" + provincia + "/cantones.json",
             data: {},
             success: function(data) {
                 agregarCantones(data);
             }
         });

    });

        $(document).on('change', '#canton > select', function() {
   var  provincia = $('select#provincia').val();
    var canton = this.value ;
         $.ajax({
             dataType: "json",
             url: "https://ubicaciones.paginasweb.cr/provincia/" + provincia + "/canton/" + canton + "/distritos.json",
             data: {},
             success: function(data) {
                 agregarDistritos(data);
             }
         });

    });

    function agregarProvincias(data) {
        var html = "<select id='provincia'>";
        for (key in data) {
            html += "<option value='" + key + "'>" + data[key] + "</option>";
        }
        html += "</select";
        $('#provincia').html(html);
    }

    function agregarCantones(data) {
        var html = "<select>";
        for (key in data) {
            html += "<option value='" + key + "'>" + data[key] + "</option>";
        }
        html += "</select";
        $('#canton').html(html);
    }

    function agregarDistritos(data) {
        var html = "<select>";
        for (key in data) {
            html += "<option value='" + key + "'>" + data[key] + "</option>";
        }
        html += "</select";
        $('#distrito').html(html);
    }

    });

y lo cargo en el siguiente html:

<html>

    <head>
        <title>Obteniendo las provincias</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <meta charset="utf-8">
        <script type="text/javascript" src="js/js_pronvincias_cantontes_distritos.js"></script>

    </head>
        <br>
        <div id="provincia"></div>
         <div id="canton"></div>
         <div id="distrito"></div>
    </body>
</html>

mi pregunta es como puedo obtener los valores de los div para luego hacer un insert en una base de datos en php.

1
  • disculpa se me olvido eso , es con php el 14 dic. 2017 a las 5:26

1 respuesta 1

2

Necesitas una función ajax que te mande los datos a un PHP, agregué a tu código en las funciones Agregar* un id a los select para poder identificarlos, agregue un botón y su función .click como ejemplo para enviar los datos (no olvides cambiar la url de tu php).

$(document).ready(function() {

$("#ok").click(function(){
	$.ajax({
		type: "POST",
		url: "agregar.php", //no olvides cambiar la ruta a tu php
		data: {"provincia":$("#provincias").val(),"canton":$("#cantones").val(),"distrito":$("#distritos").val()},
		success: function (datos) {
		    console.log('enviado a BD');							
		},
		error: function (er) {
		    console.log(er.error);
		}
	});
});

$.ajax({
	dataType: "json",
	data: [],
	url: "https://ubicaciones.paginasweb.cr/provincias.json",
	type: 'GET',
	crossDomain: true,
	success: function(data) {
		agregarProvincias(data);
	}
});


$(document).on('change', '#provincia > select', function() {
	var provincia = this.value;
	$.ajax({
		dataType: "json",
		url: "https://ubicaciones.paginasweb.cr/provincia/" + provincia + "/cantones.json",
		data: {},
		success: function(data) {
			agregarCantones(data);
		}
	});
});

$(document).on('change', '#canton > select', function() {
	var  provincia = $('select#provincia').val();
	var canton = this.value ;
	$.ajax({
		dataType: "json",
		url: "https://ubicaciones.paginasweb.cr/provincia/" + provincia + "/canton/" + canton + "/distritos.json",
		data: {},
		success: function(data) {
			agregarDistritos(data);
		}
	});
});

function agregarProvincias(data) {
	var html = "<select id='provincias'>";
	for (key in data) {
		html += "<option value='" + key + "'>" + data[key] + "</option>";
	}
	html += "</select";
	$('#provincia').html(html);
}

function agregarCantones(data) {
	var html = "<select id='cantones'>";
	for (key in data) {
		html += "<option value='" + key + "'>" + data[key] + "</option>";
	}
	html += "</select";
	$('#canton').html(html);
}

function agregarDistritos(data) {
	var html = "<select id='distritos'>";
	for (key in data) {
		html += "<option value='" + key + "'>" + data[key] + "</option>";
	}
	html += "</select";
	$('#distrito').html(html);
}

});
<html>

    <head>
        <title>Obteniendo las provincias</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <meta charset="utf-8">
        <script type="text/javascript" src="js/js_pronvincias_cantontes_distritos.js"></script>

    </head>
        <br>
        <div id="provincia"></div>
         <div id="canton"></div>
         <div id="distrito"></div>
         <br>
         <br>
         <button id="ok">Enviar a BD</button>
    </body>
</html>

En tu PHP necesitas obtener los valores enviados con Ajax utilizando $_POST

<?php
$sqli=mysqli_connect('tuhost', 'tuuser', 'tupass', 'tuBD');
// ojo los POST son los valores en ajax [data]
$provincia = $_POST["provincia"];
$canton = $_POST["canton"];
$distrito = $_POST["distrito"];
//puede cambiar la sintaxis de tu tabla
$query = mysqli_query($sqli,"INSERT INTO tuTabla VALUES ('$provincia','$canton','$distrito')");
?>
2
  • amigo gracias por la pronta respuesta, te comento que segui exactamente tu ejemplo pero al final sale el mensaje de "enviado a BD" pero no se inserto nada en la base de datos, podrá ser algún error en el código ? el 14 dic. 2017 a las 6:21
  • muchas gracias, parece fue error mio, funciona perfectamente el 14 dic. 2017 a las 16:59

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.