Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery AJAX to retrieve PHP variable

I have a php script that makes my page load slowly because it fetches API data from another site and parses it so I want to make it load last. I'm reading AJAX is the way to go because it is asynchronous. Below is my AJAX code so far. All I want to do at the moment is have AJAX fetch a variable from PHP and display it but I can't get it to work. I think I'm really close though.

Here is the DIV I want it to load to and the script trigger.

<div id="results"></div>
<script type="text/javascript">ajax_lastcount();</script>

Here is the AJAX script

<script type="text/javascript">
function ajax_lastcount() {
var hr = new XMLHttpRequest();
hr.open("GET", "/viewcount.php", true);
hr.setRequestHeader("Content-type", "application/json", true);
hr.onreadystatechange = function() {
   if(hr.readyState == 4 && hr.status == 200) {
       var data = JSON.parse(hr.responseText);
       var results = document.getElementById("results");
       results.innerHTML = data;

       }
       }
     }
     hr.send(null);
     results.innerHTML = "requesting...";
}
</script>

Here is viewcount.php page

header("Content-type", "application/json");
$lastcount = "ten";
echo json_encode($lastcount);
like image 231
The Fourth Hamster Avatar asked Mar 12 '26 17:03

The Fourth Hamster


1 Answers

Using jQuery this could be achieved by this code (called automatically after the page's DOM is loaded):

$(document).ready(function() {
    $.ajax({
        url: '/viewcount.php',
        type: 'get',
        dataType: 'json',
    })
    .success(function(data) {
        $('div#results').html(data);
    });
});

If you want to perform simplified GET or POST request, you can also call this instead:

$(document).ready(function() {
    $.get('/viewcount.php', {'optional_params_object':'value'})
    .success(function(data) {
        $('div#results').html(data);
    });
});

or

$(document).ready(function() {
    $.post('/viewcount.php', {'optional_params_object':'value'})
    .success(function(data) {
        $('div#results').html(data);
    });
});
like image 129
shadyyx Avatar answered Mar 15 '26 05:03

shadyyx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!