Jump to content

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>
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.