How to use AJAX?

14

It is more or less what AJAX is. However, it is still not clear to me how to use it, and I would like to learn how to use it because I see that it is something today.

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

    
asked by Hoose 21.08.2016 в 03:28
source

5 answers

23

Briefly

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

The main thing about AJAX is that it is done in an asynchronous way . And it's asynchronous in terms of the overall load of the page, since it allows you to make a request once the page has been obtained, without having to reload it.

When to use it

  • Update the page without needing to reload it in the browser.
  • Request data from the server (after the page has been loaded).
  • Receive data from a service (after the page has been loaded).
  • Send data to the server (in the background).

Reading your question, it seems to me that you do not even know what to use it yet ... Well, first I think you should think about what data you want to get from the web when the page is loaded. And this would be, for example, when the user clicks on some element, that seeks 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)
        }
    }

}

Example call:

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 a page generated with PHP, it can be a common HTML, it can be a WebService, it can be any web resource that you can think of.

More info: MDN > AJAX > First Steps

    
answered by 21.08.2016 / 14:49
source
6

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

Example

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

Here are some interesting links:

answered by 26.08.2016 в 12:49
6

I have a somewhat basic example of AJAX. You must use PHP on the server side and jQuery on the client (bootstrap for the design).

Insert the code in your PHP server and name it "ajaxSleep.php", it will return the variables that 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 AJAX of jQuery, name it as you see fit, and save it with "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 .css of bootstrap 3 and the .js of bootstrap 3 and jQuery 3

Paste everything on a PHP 5.6 server or higher. The parameters travel from the form to the server via AJAX, and PHP is responsible for returning the same values.

    
answered by 21.08.2016 в 19:14
0

In JQuery you have good material to use ajax: link

JQuery is a great library of javascript functions for those of us who are lazy and in a hurry.

    
answered by 26.08.2016 в 12:38
-2

With Jquery, I send you an example that I use very frequently for the use of ajax, and 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.

    
answered by 05.10.2017 в 05:30