17 votes

How to use AJAX?

It pretty much 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 elementary 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?

25voto

Mariano Points 21056

Briefly

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

The main thing of AJAX is that it is asynchronous. And it is asynchronous in terms of the overall load of the page, as it allows you to make a request once the page has already been obtained, without the need of recharging.

When to use it

  • Update the page without need of 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 not even you know for what use it is still... Well, first I think that you should think about what data you want to obtain from the web when you already loaded the page. And this would be, for example, when the user clicks on some element, that look for more information from the other 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 of call:

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



Do I need a language for server-side like PHP?

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


More info: MDN > AJAX - > First Steps

6voto

edgardo001 Points 96

I have an example of something basic of AJAX. You must use PHP for server side and jQuery on the client side (bootstrap for layout).

Insert the code in your server PHP and name it as "ajaxSleep.php" you will return the variables that I 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, jQuery, name it as you think convenient, and guardalo 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 .css of bootstrap 3 and .js of bootstrap 3 and jQuery 3

Paste everything in a server with PHP 5.6 or greater. The parameters come from the form to the server via AJAX, and PHP takes care of returning the same values.

6voto

eledgaar Points 1210

By staying a little bit a day, since SS6 came into our lives (although it seems that many of you resist) we have available the API fetch to enable us 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:

0voto

Guillermo Points 40

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

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

-3voto

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

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X