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);
XMLHttRequestcall. Do you want us to transform this into a jQuery AJAX request?$.ajax({ url: "/viewcount.php" }).done(function(data) { $('#results').html(data); });You may have to go through data if it is json, but a break point on it will let you know.