php - How to make web page display only recent update rather than reload using AJAX

973

I made a table on my web page, that reloads every ten seconds to get new information inputted by users, if any. The thing is, I don't want the whole table to reload every ten seconds, I just want the table to display only new updates that are not on the table already. Below is the code I used for reloading the page.

function process(xmlHttp, i) {
  if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
    //value = encodeURIComponent( objRef.value );
    xmlHttp.open("GET", "php/AjaxBody.php?value=" + i, true);
    xmlHttp.onreadystatechange = handleServerResponse;
    xmlHttp.send(null);
  } else {
    alert("Hold on");
  }
}

function handleServerResponse() {
  if (test.readyState == 1 || test.readyState == 2 || test.readyState == 3) {}
  if (test.readyState == 4) {
    if (test.status == 200) {
      txtResponse = test.responseText;
      bodyDiv = document.getElementById("body");
      bodyDiv.innerHTML = txtResponse;
    } else {
      alert("Error with the xmlHttp status");
    }
  }
  /*
    else{
        alert("Error with the xmlHttp readystate: " + x.status);
    } */
}

ThetxtResponse returns the whole table that is reloaded onto thediv =body, I would like to know how to go about this, and I would also like it to be native JavaScript ("I don't mind XML, to change the way the information is returned")

203

Answer

Solution:

I think you can add the limit in your url. Something like this should work fine.

function process(xmlHttp, i, max_id) {
  if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
    //value = encodeURIComponent( objRef.value );
    xmlHttp.open("GET", "php/AjaxBody.php?value=" + i + "&max_id=" + max_id, true);
    xmlHttp.onreadystatechange = handleServerResponse;
    xmlHttp.send(null);
  } else {
    alert("Hold on");
  }
}
510

Answer

Solution:

You could also add a datetime to your objects like a created date and a last modified date. Then do some checks and see if something is new.

Have a look at the javascript framework KnockoutJS if you want to some very complex changetracking, it does a lot for you but it has a relatively high learning curve.

People are also looking for solutions to the problem: php - Get the first key in an associative array

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.