JQuery AJAX to get PHP variable

I have a php script that loads my page slowly because it fetches API data from another site and parses it, so I want it to load last. I am reading AJAX - this is the way to go because it is asynchronous. Below is my AJAX code. All I want to do at the moment is get the AJAX variable from PHP and display it, but I cannot get it to work. I think I am really close.

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

<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 the viewcount.php page

header("Content-type", "application/json");
$lastcount = "ten";
echo json_encode($lastcount);

      

+3


source to share


1 answer


Using jQuery this can be achieved with this code (automatically called after the DOM page has loaded):

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

      

If you want to execute a simplified query GET

or POST

, you can also call this:



$(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);
    });
});

      

+3


source







All Articles