Javascript

Uso de Ajax en una página web

6 mayo, 2021
6,313 lecturas
Cómo usar AJAX en una página web con Fetch

QUE ES AJAX
es una técnica de desarrollo web para crear aplicaciones interactivas 

COMO FUNCIONA AJAX
Se ejecutan en el cliente, es decir, en el navegador de los usuarios mientras se mantiene la comunicación asíncrona con el servidor en segundo plano. 
De esta forma es posible realizar cambios sobre las páginas sin necesidad de recargarlas, mejorando la interactividad, velocidad y usabilidad en las aplicaciones.

QUE TECNOLOGIAS INTERVIENEN

HTML JS PHP MYSQL

EJEMPLO PRÁCTICO
IMPLEMENTAR UN BUSCADOR DE CIUDADES SENCILLO

index.html

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>EJEMPLO DE AJAX</title>
    <style>
        .texto{ color:red}
    </style>
</head>
<body>
<input type="text" placeholder="Ingrese Ciudad a buscar:" id="txtbuscar">
<div id="resultados"></div>
<script>
document.getElementById("txtbuscar").addEventListener("keyup",(e)=>{
    const data = { texto : e.target.value }
    fetch("http://localhost/ajax/respuesta.php",{
        method:'POST',
        body: JSON.stringify(data),
        headers:{
            'Accept' : 'application/json',
            'Content-Type' : 'application/json',
        }
    }).then(response => {
        return response.json()
    }).then(data =>{        
        if(data.success){
            document.getElementById("resultados").innerHTML = '<p class="texto"> ID :'+ data.ciudad.id +', NOMBRE: '+ data.ciudad.nombre+' POBLACIÓN : '+ data.ciudad.poblacion +' </p>'
        }else{
            document.getElementById("resultados").innerHTML = '<p>'+ data.mensaje +' </p>'
        }
    }).catch(error =>console.error(error));
})


</script>
</body>
</html>

 

respuesta.php

<?php
// CONSULTAS A LA BASE DE DATOS
$data = ["success"=>false];
$_post = json_decode(file_get_contents('php://input'),true);
if(isset($_post['texto'])):
    // array de ciudades
    $ciudades = array(
        array('id'=>1,'nombre'=>'Arequipa','poblacion'=> 15000000),
        array('id'=>2,'nombre'=>'Yanahuara','poblacion'=> 120000),
        array('id'=>3,'nombre'=>'Mollendo','poblacion'=> 100000)
    );
    $r = array_search($_post['texto'], array_column($ciudades,'nombre'),true);
    if($r>-1)
        $data = ["success"=>true,'ciudad'=>$ciudades[$r],'mensaje'=>"EXISTEN COINCIDENCIAS"];
    else
        $data = ["success"=>false,'mensaje'=>"NO EXISTEN COINCIDENCIAS"];
endif;
die(json_encode($data));

 

 

 

Tutoriales Recomendados

Sigue explorando publicaciones de la misma categoría

Ver todos