How to use AJAX?

I pretty much know what AJAX is. However, it is not yet clear to me how to use it, and I would like to learn how to use it because I see that it is something Elementary today.

I have searched tutorials on the Internet, but they are mostly outdated and old. My question is: Could you give me some simple code example they have and how to learn to use it? Do I need a server-side language like PHP?

 17
Author: Hoose, 2016-08-21

5 answers

Briefly

AJAX is a technique for making a request to a web resource. For example, reading a web page.

The main thing about AJAX is that it is done asynchronously . And it is asynchronous in terms of the global page load, since it allows to make a request once the page has already been fetched, without needing to reload it.

When to use it

  • refresh the page without reloading it in the browser.
  • Request data from the server (after the page has loaded).
  • receive data from a service(after the page has loaded).
  • send data to the server (in the background).

Reading your question, it seems to me that you don't even know what to use it for yet... Well, first I think you should think about what data you want to get from the web when the page has already loaded. And this would be, for example, when the user clicks on some element, looking for more information from another side,or similar.

Code example

function solicitudAJAX(url){
    
    //Enviar con AJAX
    var http_request = false;

    //Crear el objeto
    if (window.XMLHttpRequest)
        http_request = new XMLHttpRequest();
    else if (window.ActiveXObject)
        http_request = new ActiveXObject("Microsoft.XMLHTTP"); //para IE6-
    else
        return false; //Error al crear el request

    //asignamos una función que se llamará (asincrónicamente) 
    //  cuando cambie el estado de la petición
    http_request.onreadystatechange = cambiaEstadoDelRequest;
    
    //hacemos el request
    http_request.open("GET", url, true);
    http_request.send(null);
    return true;
}

function cambiaEstadoDelRequest() {
    if (http_request.readyState == 4) { // 4 significa que terminó
        if (http_request.status == 200) { //200 es la respuesta "OK" del server
            //acá leemos la respuesta (la página devuelta)
            var respuesta = http_request.responseText;
            
            //Acá el código que parsee a la respuesta <------
            
        } else {
            //El server tuvo otra respuesta (Por ej: 404 not found)
        }
    }

}

Call example:

solicitudAJAX("http://www.midominio.com/datos.html?buscar=algo");


Do I need a server-side language like PHP?

No. You need to define what you want to do. It can be getting a page generated with PHP, it can be a common HTML, it can be a WebService, it can be any web resource you can think of.


More info: MDN > AJAX > first Steps

 25
Author: Mariano, 2020-06-11 10:54:57

For keeping us a little up to date, since ES6 came into our lives (although it seems that many resist) we have the API fetch available to make AJAX calls.

Example

fetch('https://somedomine.com/some/url', {
    method: 'get'
}).then(response => {
  // Response :)
}).catch(err => {
  // Error :(
})

I leave you some interesting links:

 6
Author: eledgaar, 2016-08-26 10:49:41

I have a somewhat basic AJAX example. You should use server-side PHP and client-side JQuery (bootstrap for layout).

Insert the code into your PHP server and name it as " ajaxSleep.php", will return the variables you send by AJAX from the client.

<?php
    $nombre = $_POST["nombre"];
    $apellido = $_POST["apellido"];
    $telefono = $_POST["telefono"];
    sleep(4);//simulamos tiempo de espera de algunos segundos
    echo ("Tus datos: " . $nombre . " - " .     $apellido . " - " . $telefono);
?> 

This is the code that implements jQuery'S AJAX, name it as you see fit, and save it next to " ajaxSleep.php":

<html>
<body>

    <div class="container">
        <h2>Modal Example</h2>

        <div class="jumbotron">
            <h1>Hello, world!</h1>
            <p id="lblDatos">......</p>
            <button id="btnModal" class="btn btn-primary">Abrir modal</button>
        </div>

        <!-- Modal -->
        <div class="modal fade" id="myModal" role="dialog">
            <div class="modal-dialog">
                <!-- Modal contenido-->
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                        <h4 class="modal-title">Modal Header</h4>
                    </div>
                    <div class="modal-body">
                        <label for="txtNombre">Nombre: </label>
                        <input type="text" class="form-control" id="txtNombre"/>

                        <label for="txtApellido">Apellido:</label>
                        <input type="text" class="form-control" id="txtApellido"/>

                        <label for="txtTelefono">Telefono:</label>
                        <input type="text" class="form-control" id="txtTelefono"/>
                    </div>
                    <div class="modal-footer">                            
                        <button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
                        <button type="button" class="btn btn-success" id="btnGuardar">Guardar</button>
                        <img src="img/cargandoPaginaWeb.gif" class="img-rounded" height="30px" width="30px" id="imgLoad" style="display:none">
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!--haca todos los script-->
    <!--Siempre debe ir jQuery primero q bootstrap-->
    <script src="js/jquery-3.1.0.js"></script>  
    <script src="js/bootstrap.js"></script>        
    <script type="text/javascript">  
        $(document).ready(function() { 
            $('#btnModal').click(function(event){
                clearModal();
                $('#myModal').modal('show');                
            }); 
            $('#btnGuardar').click(function(event){                    
                var n= $('#txtNombre').val();
                var a = $('#txtApellido').val();
                var t = $('#txtTelefono').val();
                $.ajax({
                    type: "POST",
                    data: {"nombre" : n, "apellido" : a, "telefono" : t},
                    url: "ajaxSleep.php",
                    beforeSend: function () {
                        $('#imgLoad').show();
                    },
                    success: function(response) { 
                        $('#lblDatos').text(response);                           
                    },
                    error: function(jqXHR, textStatus, errorThrown){
                        //if(textStatus === 'timeout'){alert('Failed from timeout');}   
                        if (jqXHR.status === 0) {alert('Not connect: Verify Network: ' + textStatus);}
                        else if (jqXHR.status == 404) {alert('Requested page not found [404]');} 
                        else if (jqXHR.status == 500) {alert('Internal Server Error [500].');}
                        else if (textStatus === 'parsererror') {alert('Requested JSON parse failed.');}
                        else if (textStatus === 'timeout') {alert('Time out error.');} 
                        else if (textStatus === 'abort') {alert('Ajax request aborted.');} 
                        else {alert('Uncaught Error: ' + jqXHR.responseText);}
                    },
                    timeout: 5000
                    //timeout: 1000//para probar timeout
                }).always(function(){
                    $('#imgLoad').hide();
                    $('#myModal').modal('toggle');//Verificar uso 
                    clearModal();
                });
                event.preventDefault();
            });  
            function clearModal(){
                //Limpio las cajas de texto del modal
                $('.modal-body input').val('');
            }    
        });            
    </script>

</body>
</html>

Remember to add the .Bootstrap css 3 and the .bootstrap js 3 and jQuery 3

Paste everything into a PHP 5.6 or higher server. The parameters travel from the form to the server via AJAX, and PHP takes care of returning the same values.

 6
Author: edgardo001, 2016-09-15 07:08:50

In jquery you have good material to use ajax: https://learn.jquery.com/ajax/jquery-ajax-methods /

JQuery is a magnificent library of javascript functions for which we are lazy and go in a hurry.

 0
Author: Guillermo, 2016-08-26 10:38:25

With Jquery, I send you an example that I use it very often for the topic of using ajax I use it to extract data in Json format.

    $(document).ready(function () {

var config = {
    url: '../../aplicacion/crud/index.php',
    variables: 'tabla'
};
var fuentedata = sendData(config);
 function  sendData(config)
 {//json captura
 var json = null;
 $.ajax({
    'type': "POST",
    'data': config,
    'async': false,
    'global': false,
    'url': '' + config.url,
    'dataType': "json"
    , 'beforeSend': function (data)
    {
       // console.log('... cargando...');
    }
    , 'error': function (data) {
        //si hay un error mostramos un mensaje
        console.log('Tenemos problemas Houston ' + data);
    },
    'success': function (data) {
        json = data;
    }
    });
    return json;
}

});

I hope to be of help.

 -3
Author: Christian Miranda Zambrano, 2017-10-05 03:30:45