Sunday, 14 June 2020

search page using exploda and ajax

dbconnect

<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'lesson44';

if($mycon = @mysqli_connect($host, $user, $pass)){

mysqli_select_db($mycon, $dbname);

}


?>


search.php

<?php
require 'dbconnect.php';
?>

<?php

if (isset ($_GET ['s_text'])){
$s_text = $_GET ['s_text'];
echo 'u entered:'.$s_text. '<br/>';
$namesar = explode(' ' , $s_text);
$size= sizeof($namesar);

$i=0;
while ($i < $size)
{
$search= $namesar[$i]  ;
echo 'search engine started' . $search;
$query = "SELECT `name` FROM `foods` WHERE `name` LIKE '%$search%' ";
$query_run = mysqli_query($mycon, $query);
$num_rows = mysqli_num_rows($query_run);

if ($num_rows >= 1) {
echo '<h1>' .$num_rows.'results found</h1>';
while ($row = mysqli_fetch_assoc($query_run)){
echo $row['name']. '<br><br>';
}
}else{
echo 'no results found';
}



$i++;
}

}


?>


index.php


<html>
<head>
<script>
function findmatch(){
if(window.XMLHttpRequest){xmlhttp = new XMLHttpRequest();}
else{xmlhttp =new ActiveXobject('Microsoft.XMLHTTP');}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{document.getElementById('rdiv').innerHTML = xmlhttp.responseText;}
}
xmlhttp.open('GET', 'search.php ?s_text='+document.search.s_text.value, true);
xmlhttp.send();

</script>

 </head>
<body> 
<form name="search" >
<!-- if no method is mentioned, default as get method, we not mentoned method, xml get method, have to url add if we have submit , after clicked in submit, but we want to add using ajax using concatenatin-->
type keyword :<input type ="text" name="s_text" onkeyup="findmatch()">
</form>
<div id ="rdiv" ></div>
</body>

</html>

No comments:

Post a Comment