Jump to content

Live Database search using PHP, MySQL, and JSON


phpnewbie34

Recommended Posts

Good afternoon, 

 

I am looking to add a live search to my site.

 

My JS / HTML code is:

 

 

       <script>
    var form = document.getElementById('keywordForm');
    form.addEventListener('submit',function(e) {
        var search = form.keyword.value;
        var xhr = new XMLHttpRequest();
        xhr.open("GET","keywordsearch.php?search="+search,true);
        xhr.send();
        xhr.onreadystatechange = function() {
            if(xhr.readyState == 4 && xhr.status == 200) {
                var response = xhr.response;
            }
        };
        e.preventDefault();
    });
</script> 
    <form id="keywordForm">
    <input id="keyword" type="text" />
    <input type="submit" value="Search"/>
</form> 
 
And my PHP for the other page is:
 
<?php
if(isset($_GET['search'])) { 
 $search =   $_GET['search'];
 
   include 'dbconnect.php';
//Include code that connects to the database
    $result = mysqli_query($con, "Select * FROM pixs WHERE search=$search"  );
    $keywords = array(); 
   while ($keywords = mysqli_fetch_array($result)) { 
        $keywords[] = $keyword['keyword']; 
    } 
    echo json_encode($keywords); 
}
?>

 

I can't even get it to refresh on the first when I click on the search button.

 

Any advice / tips / examples would be amazing!

 

Try,

<form id="keywordForm" onsubmit="return false;">
    <input id="keyword" type="text" />
    <input type="submit" value="Search" />
</form> 

<script>

    var e = document.getElementById('keywordForm');
    e.addEventListener("submit", function(){listener(e)}, false);

    function listener(e) {
        var search = e.keyword.value;
        var xhr = new XMLHttpRequest();
        xhr.open("GET","keywordsearch.php?search="+search,true);
        xhr.send();
        xhr.onreadystatechange = function() {
            if(xhr.readyState == 4 && xhr.status == 200) {
                var response = xhr.response;
            }
        };
        e.preventDefault();
    }    
</script>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.