AJAX - Load values of .php in a select - Provinces

2

I have to load the provinces, they are in an .sql file that I load in the phpmyadmin, in a select within a formulario .

The form has a select are the following information:

<tr>
    <td align=right>Provincia:</td><td align=left colspan=3>
        <select name="provincia" id="idprovincia">
            <option value="-">Seleccione una Provincia...
        </select>
    </td>
</tr>

How do I charge the provinces in the select through AJAX?

I tried the following but it gives me the following error, although I think the code is not correct:

jquery.js:18 XMLHttpRequest cannot load file:///D:/Javascript/OSMAR/provincias_exam.php. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

Código intentado Javascript:

//Al cargar el documento...
$(document).ready(function(){
    iniciar();
    //Método 1.
    // $.ajax({
        // type: "GET",
        // url: "provincias_exam.php",
        // success: function (response){
            // $("#idprovincia").html(response).fadeIn();
        // }
    // });

    //Método 2.
    //$("#idprovincia").load("provincias_exam.php");
});//fin ready 


//Método 3.
var arrayProvincias = []; //array de objetos donde almacenaremos los datos de la consulta.
function iniciar(){
    $.ajax({
        url: 'provincias_exam.php',
        dataType: 'json',
        async: true,  //Asíncrono
        success: resultadoPeticion, 
        error: function(){
            alert("Error en la petición a la base de datos");
        }
    });    
}


//Llamamos a la función para imprimir resultados.
function resultadoPeticion(resultados){ 
    var texto = "";
    //Recorremos los valores con un for each.
    $.each(resultados, function(indice, valor){
        texto += valor.nom_prov;
        arrayProvincias[arrayProvincias.length] = valor;
    });         
    //Agregamos en el id "idprovincia" el valor que tenga la variable texto. (todas las provincias).
    $("#idprovincia").html(texto);
    //Imprimimos todas las provincias en el select.
    rellenarSelect();
}


//Rellenamos el select con las provincias.
function rellenarSelect(){
    var imprimir = "";
    for (var i=0; i<arrayProvincias.length; i++){
        imprimir += "<option value='"+i+"'>"+arrayProvincias[i].nom_prov+"</option>";
    }
    $("#idprovincia").html(imprimir);
}

External required file for the loading of the provinces:

CommunitiesProvinces.sql table comunidades

  id_com | nom_com
    1    | 'Euskadi'
    2    |'Galicia'
    3    |'Catalunya'
    4    |'Andalucia'
    5    | 'Castilla Leon'
    6    | 'Castilla La MAncha'

table provincias

id_prov'| 'id_com'| 'nom_prov'
    1   |        1| 'Bizkaia'
    2   |        1| 'Gipuzkoa'
    3   |        1| 'Araba'
    4   |        2| 'A Coruña'
    5   |        2| 'Lugo'
    6   |        2| 'Ourense'
    7   |        2| 'Pontevdra'
    8   |        3| 'Barcelona'
    9   |        3| 'Tarragona'
    10  |        3| 'Lleida'
    11  |        3| 'Girona'
    12  |        4| 'Almeria'
    13  |        4| 'Cadiz'
    14  |        4| 'Cordoba'
    15  |        4| 'Granada'
    16  |        4| 'Huelva'

conexion2.php:

<?

$dbserver = "nombre_servidor";
$dbuser = "usuario";
$password = "clave";
$dbname = "nombre_base_datos";


$con = new mysqli($dbserver, $dbuser, $password,$dbname);
if(!$con) {
    echo "No se pudo conectar a la base de datos";
  }

?>

provincias_exam.php:

<?php
    include("conexion_2.php");


if(!$con) {
    echo "No se pudo conectar a la base de datos";
  }


$sql = "SELECT * FROM provincias";
$result = $con->query($sql);

$rowdata=array();
$i=0;
        while ($row = $result->fetch_array())
        {
            $rowdata[$i]=$row;
            $i++;           
        }
echo json_encode($rowdata);
?>
    
asked by omaza1990 05.06.2017 в 15:41
source

2 answers

2

Try this.

I've put everything into a single function, because I create functions that are only called once I think it's not necessary.

function iniciar(){
    $.ajax({
        url: 'provincias_exam.php',
        dataType: 'json',
        error: function(){
            alert("Error en la petición a la base de datos");
        }
    }).done( function(valor) {
       var texto = "";
       //Recorremos los valores con un for each.
       $.each(function(i, valor){
           texto += "<option value='"+i+"'>"+valor+"</option>";
       });         
       //Agregamos en el id "idprovincia" el valor que tenga la variable texto. (todas las provincias).
       $("#idprovincia").html(texto);
    });    
}
    
answered by 05.06.2017 в 16:57
2

This would be the solution to your query. However, take into account the commented lines. Maybe they'll help you find and better understand the error in your code. Greetings.

function obtenerProvincias() {
        $.ajax({
            url: 'provincias_exam.php', //Si el doc php esta en mismo nivel seria directo. Caso contrario si el archivos php esta en una carpeta abría que mapearla bien. Ejemplo: url:'php/provincias_Exam.php'
            type: 'post',
            success: function (r) { // te recomiendo que imprimas las respuesta "console.log(r)" para que veas como te esta devolviendo la estructura tu php.
                $("#idprovincia").empty();
                r = JSON.parse(r);
                sedeItem = crearElemento('option', '__', '__', 'Seleccione...', '__', '__');
                sedeItem.setAttribute('value', '');
                $("#idprovincia").append(sedeItem);
                for (i = 0; i < r.length; i++) {
                    option = crearElemento('option', '__', '__', r[i]['id_prov'], '__', r[i]['nom_prov']);
                    $("#idprovincia").append(option);
                }
            }
        });
    }
    function crearElemento(elemento, identificador, clase, texto, ruta, valor) {
        item = document.createElement(elemento);
        if (identificador !=='__'){ item.id = identificador; }
        if (clase !=='__') { item.className = clase; }
        if (texto !=='__') { item.innerText = texto; }
        if (ruta !== '__') { item.dataset.cargarVista = ruta; }
        if (valor !== '__') { item.value = valor; }
        return item;
    }
    
answered by 05.06.2017 в 21:34