Ver Mensaje Individual
  #10 (permalink)  
Antiguo 04/10/2014, 14:51
darktests
 
Fecha de Ingreso: septiembre-2014
Mensajes: 6
Antigüedad: 10 años, 5 meses
Puntos: 0
Respuesta: Autocompletar form con info de DB

Vale, he conseguido hacer parte de lo que quería, pero ahora me encuentro con otro error. He conseguido detectar que al dar al botón buscar se haga el query a la DB y tengo tres supuestos:
  1. El código postal no existe -> Arroja un mensaje de error
  2. El código postal existe y solo es usado por una población -> Rellena el form con la info de la DB.
  3. El código postal existe pero más de una poblaión lo usa -> Abre un popup para seleccionar la localidad correcta.

Los dos primeros supuestos funcionan perfectamente. Con el tercero he conseguido hacer que el script detecte que el código postal está compartido por más de una persona pero en vez de abrir el popup inserta la información de este en el form. (Ver imagen) Voy a actualizar el post principal con el código que estoy usando.



Edit: No puedo actualizar el post principal asique lo pongo aquí:

index.php

Código PHP:
<input type="text" maxlength="5" class="form-control" id="postal_code" name="postal_code" placeholder="Código postal" pattern="[0-9]{5}">
<
button class="btn btn-info btn-flat" type="button" onclick="updateCityState();">Buscar</button>
<
input type="text" id="city" class="form-control" placeholder="Población">
<
input type="text" id="state" class="form-control" placeholder="Provincia">
........
<
script src="popup.js"></script>
<script>var ajax = getHTTPObject();

        function getHTTPObject()
        {
            var xmlhttp;
            if (window.XMLHttpRequest) {
              // code for IE7+, Firefox, Chrome, Opera, Safari
              xmlhttp=new XMLHttpRequest();
            } else if (window.ActiveXObject) {
              // code for IE6, IE5
              xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            } else {
              //alert("Your browser does not support XMLHTTP!");
            }
            return xmlhttp;
        }

        function updateCityState()
        {
            if (ajax)
            {
                var zipValue = document.getElementById("postal_code").value;
                if(zipValue)
                {
                    var url = "get_cities.php";
                    var param = "?postal_code=" + escape(zipValue);

                    ajax.open("GET", url + param, true);
                    ajax.onreadystatechange = handleAjax;
                    ajax.send(null);
                }
            }
        }
        function handleAjax()
        {
            if (ajax.readyState == 4)
            {
                if( ajax.responseText.length ) {
                    citystatearr = ajax.responseText.split(",");
                    city.value = citystatearr[0]; 
                    state.value = citystatearr[1];
                }else{
                    city.value = "No existe";
                    state.value = "No existe";
                }
            }
        }
    </script> 
get_cities.php

Código PHP:
<?php
include_once('../../../connect.html');
//perform lookup
$title = ($_GET['postal_code']);
$statement $connection->prepare ("SELECT city, state FROM cities, states WHERE cities.state_id = states.state_id AND cities.postal_code = ?");
$statement->execute(array($title));
$statement->setFetchMode(PDO::FETCH_ASSOC);

//print out results

//print_r($r);
//if (count($r)>4) {
//        echo "Muchos","Demasiados";
//    }else{

$items = array();
while (
$r $statement->fetch()) {
    
//$arrayName = array($r = $statement->fetch());
    
$items[] = $r;
}

if (
count($items) == '1'){

    
$newArray $items[0];
    echo 
$newArray['city'].",".$newArray['state']; 
}elseif (
count($items) == '0'){
        echo 
"Doesn't exist".","."Doesn't exist";
    }else{
?>
<script type="text/javascript">
centerPopup();
        loadPopup();
</script>

        <div id="popupContact">
        <a id="popupContactClose">x</a>
        <h1>Title of our cool popup, yay!</h1>
        <p id="contactArea">
            Here we have a simple but interesting sample of our new stuning and smooth popup. As you can see jQuery and CSS does it easy...
            <br/><br/>
            We can use it for popup-forms and more... just experiment!
            <br/><br/>
            Press ESCAPE, Click on X (right-top) or Click Out from the popup to close the popup!
            <br/><br/>
            <a href="http://www.yensdesign.com"><img src="logo.jpg" alt="Go to yensdesign.com"/></a>
        </p>
    </div>
    <div id="backgroundPopup"></div>
    <?php
}

?>
popup.js
Código PHP:
/***************************/
//@Author: Adrian "yEnS" Mato Gondelle
//@website: www.yensdesign.com
//@email: [email protected]
//@license: Feel free to use it, but keep this credits please!                  
/***************************/

//SETTING UP OUR POPUP
//0 means disabled; 1 means enabled;
var popupStatus 0;

//loading popup with jQuery magic!
function loadPopup(){
    
//loads popup only if it is disabled
    
if(popupStatus==0){
        $(
"#backgroundPopup").css({
            
"opacity""0.7"
        
});
        $(
"#backgroundPopup").fadeIn("slow");
        $(
"#popupContact").fadeIn("slow");
        
popupStatus 1;
    }
}

//disabling popup with jQuery magic!
function disablePopup(){
    
//disables popup only if it is enabled
    
if(popupStatus==1){
        $(
"#backgroundPopup").fadeOut("slow");
        $(
"#popupContact").fadeOut("slow");
        
popupStatus 0;
    }
}

//centering popup
function centerPopup(){
    
//request data for centering
    
var windowWidth document.documentElement.clientWidth;
    var 
windowHeight document.documentElement.clientHeight;
    var 
popupHeight = $("#popupContact").height();
    var 
popupWidth = $("#popupContact").width();
    
//centering
    
$("#popupContact").css({
        
"position""absolute",
        
"top"windowHeight/2-popupHeight/2,
        
"left"windowWidth/2-popupWidth/2
    
});
    
//only need force for IE6

    
$("#backgroundPopup").css({
        
"height"windowHeight
    
});

}


//CONTROLLING EVENTS IN jQuery
$(document).ready(function(){

    
//LOADING POPUP
    //Click the button event!


    //CLOSING POPUP
    //Click the x event!
    
$("#popupContactClose").click(function(){
        
disablePopup();
    });
    
//Click out event!
    
$("#backgroundPopup").click(function(){
        
disablePopup();
    });
    
//Press Escape event!
    
$(document).keypress(function(e){
        if(
e.keyCode==27 && popupStatus==1){
            
disablePopup();
        }
    });

}); 
Básicamente esto se inserta en el form en vez de ejecutar el código... ¿alguna idea de por qué?

Última edición por darktests; 04/10/2014 a las 14:56