skip to Main Content

i have an issue with my input only is display me last value but the value if exist because in console and alert function is showed.
the code work perfectly some years ago and now stopped working.

I have 3 files.

  • funcionajax.js.
  • Principal.html.
  • PHPinvocado.php.
    this just return 3 records on json format, something like the following.
[{"nombre":"Josue","apellido":"Becerra","telefono":"3741021534"},{"nombre":"Ernesto","apellido":"Rodriguez","telefono":"3741034234"},{"nombre":"Alberto","apellido":"Jimenez","telefono":"3861023421"}]
  • funcionajax.js code
function MostrarDatos(){
        
        var hr = new XMLHttpRequest();
        var caja1 = document.getElementById("txtnombre");
        var caja2 = document.getElementById("txtap");
        var caja3 = document.getElementById("txttel");
    
    hr.open("GET", "PHPinvocado.php", true);
    hr.setRequestHeader("Content-type", "application/json");
    hr.onreadystatechange = function() {
        if(hr.readyState == 4 && hr.status == 200) {
            var data = JSON.parse(hr.responseText);
            
            
                    for(var obj in data){
                        
                alert("row found."+ data[obj].nombre+" "+data[obj].apellido+" "+data[obj].telefono);
                console.log(data[obj].nombre+" "+data[obj].apellido+" "+data[obj].telefono);
                
                caja1.value=""+data[obj].nombre;
                caja2.value=""+data[obj].apellido;
                caja3.value=""+data[obj].telefono;
            }
            
        }
    }
    hr.send(null);
    
}
  • Principal.html code
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>ejemplo2</title>
<script type="text/javascript" src="funcionajax.js"></script>
</head>

<body>
<label style="margin-left: 2%"><strong>Esta es la pagina del ejemplo 2:</strong></label><br><br><br>
<label style="margin-left: 2%"><strong>Nombre:</strong></label>
   <input id="txtnombre" name="nombre" type="text" />
   
<label style="margin-left: 2.5%">Apellido:</label>
   <input id="txtap" name="AP" type="text" />
   
<label style="margin-left: 3%">Telefono:</label>
   <input id="txttel" name="AM" type="text" />
   
<input type="button" onClick="MostrarDatos()" value="Buscar">
</body>
</html>
  • PHPinvocado.php
$link = mysqli_connect("localhost", "root", "root", "dbejemplo");

    if (!$link) {
        die("No se puede conectar a la base de datos: " . mysqli_connect_error());
    }

$sql = "SELECT *FROM tablaalunmos";

$result = mysqli_query($link, $sql);

if (mysqli_num_rows($result) > 0) {

    
    while($row = mysqli_fetch_assoc($result)) {
        
$arreglo=array(
        "nombre"=>$row['nombre'],
        "apellido"=>$row['apellido'],
        "telefono"=>$row['telefono'],
                                                                
            );
            
    $total[]=$arreglo; //agrega una nueva fila 'registro' en la posision que le sigue...

    }

} else {
    $arreglo=array("empty"=>"No hay resulado");
    $total[]=$arreglo; 
}

mysqli_close($link);
echo json_encode($total);
?>

first rows only in console and funtion alert

last row in inputs too

2

Answers


  1. Your script does exactly what it is supposed to do: it parses an array of addresses from the JSON server response, shows them, one after another in an alert message and then puts the data values into your input fields. As you are overwriting the values into these three input fields, only the last entries will remain visible there after your loop has finished.

    In the script below I have replaced your PHP backend with a simple sample API and changed the property names accordingly:

    function MostrarDatos(){
        
        var hr = new XMLHttpRequest();
        var caja1 = document.getElementById("txtnombre");
        var caja2 = document.getElementById("txtap");
        var caja3 = document.getElementById("txttel");
    
    hr.open("GET", "https://jsonplaceholder.typicode.com/users", true);
    hr.setRequestHeader("Content-type", "application/json");
    hr.onreadystatechange = function() {
        if(hr.readyState == 4 && hr.status == 200) {
            var data = JSON.parse(hr.responseText);
            
                    // console.log(data);
                    for(var obj in data){
                        
                alert("row found."+ data[obj].username+" "+data[obj].name+" "+data[obj].phone);
                // console.log(data[obj].nombre+" "+data[obj].apellido+" "+data[obj].telefono);
                
                caja1.value=""+data[obj].username;
                caja2.value=""+data[obj].name;
                caja3.value=""+data[obj].phone;
            }
            
        }
    }
    hr.send(null);
    
    }
    <label style="margin-left: 2%"><strong>Esta es la pagina del ejemplo 2:</strong></label><br><br><br>
    <label style="margin-left: 2%"><strong>Nombre:</strong></label>
       <input id="txtnombre" name="nombre" type="text" />
       
    <label style="margin-left: 2.5%">Apellido:</label>
       <input id="txtap" name="AP" type="text" />
       
    <label style="margin-left: 3%">Telefono:</label>
       <input id="txttel" name="AM" type="text" />
       
    <input type="button" onClick="MostrarDatos()" value="Buscar">
    </body>
    </html>

    As mentioned before, using alert() as a debugging tool is not the wisest choice – but it basically works. Only: the page does not get refreshed after showing each alert message. I believe this is a change in the way modern browsers behave now. The YouTube video you are referring to appears to be seven years old and was recorded using a browser of that time with a different rendering approach.

    Also: You could simplify your script considerably by replacing the old XMLHttpRequest()-based AJAX call with a simpler promise based fetch().then() construct.

    Login or Signup to reply.
  2. As @CarstenMassmann implied in their answer: You cannot expect the browser to redraw in between function calls nor behind a modal dialogue (which blocks the UI). Just to get it back working, you could add a small delay right after assigning the values to the text fields by using a non blocking function. While this is not guaranteed to work, it probably will.

    var data = [{"nombre":"Josue","apellido":"Becerra","telefono":"3741021534"},{"nombre":"Ernesto","apellido":"Rodriguez","telefono":"3741034234"},{"nombre":"Alberto","apellido":"Jimenez","telefono":"3861023421"}];
    async function MostrarDatos() {
        var caja1 = document.getElementById("txtnombre");
        var caja2 = document.getElementById("txtap");
        var caja3 = document.getElementById("txttel");
        for(var obj in data){
            alert("row found."+ data[obj].nombre+" "+data[obj].apellido+" "+data[obj].telefono);
            console.log(data[obj].nombre+" "+data[obj].apellido+" "+data[obj].telefono);
            
            caja1.value=""+data[obj].nombre;
            caja2.value=""+data[obj].apellido;
            caja3.value=""+data[obj].telefono;
            await Sleep(100);
        }
    }
    function Sleep(milliseconds) {
        return new Promise(resolve => setTimeout(resolve, milliseconds));
    }
    

    Tested to be working in Safari, Chrome, Firefox and Edge on Mac. Here is a Fiddle

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search