简体   繁体   中英

Get text from PHP echo and update DIV using AJAX

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

I don't have an environment in which to test this right now, but my suspicion is that the window.setTimeout(update, 3000); is not what you're meaning to do.

The timeout parameter of the $.ajax function is the amount of permitted time for the request, not the interval in which it runs.

http://www.tutorialsteacher.com/jquery/jquery-ajax-method

If you're trying to have it load every 3 seconds, I'd do use the setInterval function in Javascript:

https://www.w3schools.com/jsref/met_win_setinterval.asp

function update() {
  $("#contador").load('Loading...'); 
  $.ajax({
    type: 'GET',
    url: 'number.php',
    success: function(data) {
      $("#contador").html(data);
      //$("#contador").html(''); This clears your <div>
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      $("#contador").html('Timeout...');
      console.log('TextStatus: '+textStatus);
      console.log('ErrorThrown: ' + errorThrown);
    }
});
}
$(document).ready(function() {
    setInterval(update, 3000);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM