Reputation: 197
I have an external PHP script, which outputs any new data that has been added to the database in the past 5 seconds. I use ajax and jQuery to load the data from the PHP script into a div, every 5 seconds.
My jQuery code:
function loaddata(){
$("#last_message").load("ajaxlastmessage.php");
setTimeout(loaddata, 10000);
}
loaddata();
How do I adjust this code, to only load the outputted PHP data, if there is data that has been outputted? The data is outputted from the PHP script by echoing the text in a paragraph tag.
Thanks in advance :)
Upvotes: 0
Views: 195
Reputation: 467
jQuery's load() function will immediately add the loaded script to the given element, whether it contained data or not.
If you want to analyse and see if any data is returned before you add it to your element, you need to load the data first and then do some analysis on it to determine if its empty or not before adding it to your given element.
Here's an example that will do it for you:
function loaddata() {
$.ajax({
type: "GET",
url: "ajaxlastmessage.php",
success: function(data) {
if (data.length>0) {
$("#last_message").append(data);
}
}
});
setTimeout(loaddata, 10000);
}
loaddata();
Upvotes: 1