jquery post and clear interval according to return data

function searchu(){  
    $.post("search.php", {userid: "<?php echo $userid; ?>"})
    .done(function(data) {  
    $("#chatbox").append( data );
    });
};
var Searchi= setInterval (searchu, 5000);

I am using this function to send some data to search.php. And search.php is matching data with database and returning results if there is matches. Like;

if(database match found){
do something
} else {
do not something
}

I want to stop interval if "database match found" is true. Tried using clearInterval(Searchi); in search.php and it didn't work.

How can i make it working?

Answers


You'll have to add to your done function a way to test if it completed. If your just returning plain HTML (which is horrible practice), you could do something like:

var Searchi= setInterval(searchu, 5000);

function searchu(){  
    $.post("search.php", {userid: "<?php echo $userid; ?>"})
    .done(function(data) {  
       if(data != "No Results Found"){
           window.clearInterval(Searchi);
       }
       $("#chatbox").append( data );
    });
};

But you should probably be returning a JSON, and check the number of results returned instead of a direct comparison with your string.


Need Your Help

php refresh just a part of the page

javascript php jquery

helllo so i builded a countdown with php