Ajax Live Search Javascript数据

function getData(str) {
if (str.length == 0) { 
    var target = document.querySelectorAll("#delete");
    return;
} else {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var target = document.querySelectorAll("#delete");
            for(var i=0 ; i<target.length; i++){
                target[i].innerHTML="";
                target[0].innerHTML=this.responseText;

            }


        } 
    };
    xmlhttp.open("GET", "data.php?q=" + str, true);
    xmlhttp.send();
}

}

Good morning, I have the following javascript for AJAX request on a live search. I then send this data to data.php page that checks if get request of q is empty and if its not, matching data is returned. Now, when the search box is empty, I want to show all results instead of showing no results. I tried checking if $_GET request is empty on the data.php page to output all results but it's not working. The only way I seem to be able to do something when $_GET['q'] is empty is in the javascript above in the

if(str.length==0) {
 .... 
} ; 

Now the problem I have is that I want to send all the data if search is empty but that data is in my php file so how would I send the data from php to javascript? There may be a better way to do this or is there something I don't get here?

If you want to show all search results when the search string is empty, then you can just check in data.php if the q parameter of $_GET is empty. If it is empty then data.php can return all the data. Your code can be updated as follows:

function getData(str) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var target = document.querySelectorAll("#delete");
            for(var i=0 ; i<target.length; i++){
                target[i].innerHTML="";
                target[0].innerHTML=this.responseText;

            }


        } 
    };
    xmlhttp.open("GET", "data.php?q=" + str, true);
    xmlhttp.send();
}