DO I make more than one ajax request on the same page?

1

I am doing a search in the database and returning this data in a table via ajax, then in this same table there is a column that has a link that returns more information about the data, all by ajax. The first ajax request happens as expected, but the second request the data appears and disappears from the screen quickly, I noticed this because I put an alert in ajax.responseText. My question is if I can execute two ajax requests on the same page. My code js is that aki.

function mostrar_fase()
    {
    ajax = xmlhttp();
    id_fase = document.getElementById('id_fase').value; 

    if(ajax)
    {               
        ajax.open("GET",'http://localhost/sac/Ajax/mostrar_fase/' + id_fase, true);     
        ajax.onreadystatechange = function() 
        {       
            if (ajax.readyState == 4 && ajax.status == 200)             
            {                       
                document.getElementById("resposta").innerHTML = ajax.responseText;              

            }
        }
         ajax.send();
    }
}

The impression I have is that I must zero some variable in the first ajax request. But I do not know what it would be. This code I posted is of the second request, however the first one is very similar to this one only changes a variable and the link. Thank you in advance.

    
asked by anonymous 28.06.2015 / 17:03

1 answer

2

Yes it is possible , I personally recommend using jQuery as it becomes easier to create requests via Ajax.

I've developed a small code that demonstrates two ajax requests for the same page.

HTML & JS:

<html>

    <body>

        <button id="calc1">1+2</button>
        <button id="calc2">1+3</button>

        <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script><script>$("#calc1").click(function(){
                $.ajax({
                    type: "GET",
                    url: "test.php",
                    data: { x:"1", y:"2"},
                    success: function (data){
                        alert(data);
                    }
                })
            });

            $("#calc2").click(function(){
                $.ajax({
                    type: "GET",
                    url: "test.php",
                    data: { x:"1", y:"3"},
                    success: function (data){
                        alert(data);
                    }
                })
            });

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

PHP:

<?php

$x = $_GET['x'];
$y = $_GET['y'];

echo $x+$y;

You can use the code and test it and you will see that both requirements are executed without any problems, it is up to you to adapt the code later.

    
28.06.2015 / 19:06