I'm learning HTML, PHP, AJAX and jQuery in my degree. In a practise I need to refresh a DIV container every 3 seconds without recharging the whole page.
I must use AJAX to refresh and the response need to be a random number generated in the server using PHP.
I have this:
index.php
<div id="contador">NEED TO OVERWRITE THIS TEXT</div>
number.php
<?php
echo "Number: " . rand(1,100);
?>
ajaxreload.js
function update() {
$("#contador").load('Loading...');
$.ajax({
type: 'GET',
url: 'number.php',
timeout: 3000,
success: function(data) {
$("#contador").html(data);
$("#contador").html('');
window.setTimeout(update, 3000);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#contador").html('Timeout...');
window.setTimeout(update, 3000);
}
});
}
$(document).ready(function() {
update();
});
The DIV is being updated each 3 seconds, but it isn't getting the echo response from number.php. I'm getting a very fast "Loading..." message and then "Timeout...". What is wrong? I need to use another thing instead of echo? Another type or URL data? Another AJAX function?
Thank you!
SOLVED: Thank you! Solved in the console :) The problem is that my index.php file are in the root and the number.php and ajaxreload.js in a "scripts" folder. The parameter url: 'number.php' try to load it from the div location (where index.php is) and not where script file is calling
Thank you @dan08 @Keith Chason It was the first time I use the console
$("#contador").html('');You're emptying the contents right after you set it. Also, if you're getting into the error handler, it would make sense to actually check what error is being reported.console.log(textStatus)in the error function to get more information about the error. Please add the results to your question.