This is my coding. This coding allows me to search the keyword in my database and it worked fine. But how can i search the keyword without click the search button? What i want is same as the search function in the google search. It can automatically help you search and review without hit any button.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Search Contacts</title>
</head>
<p><body>
<h3>Search Contacts Details</h3>
<p>You may search either by first or last name</p>
<form method="post" action="search.php?go" id="searchform">
<input type="text" name="question">
<input type="submit" name="submit" value="Search">
</form>
<?php
if(isset($_POST['submit'])){
if(isset($_GET['go'])){
if(preg_match("/^[ a-zA-Z]+/", $_POST['question'])){
$question=$_POST['question'];
$con = mysqli_connect("localhost","root","");
mysqli_select_db($con,"search")or die(mysqli_error($con));;
$sql="SELECT id , question FROM question WHERE question LIKE '%" . $question . "%'";
//-run the query against the mysql query function
$result=mysqli_query($con, $sql);
while ($row=mysqli_fetch_array($result)){
$question =$row['question'];
$id=$row['id'];
echo "<ul>\n";
echo "<li>" . " " . $question . "</li>\n";
echo "</ul>";
}
}
else{
echo "<p>Please enter a search query</p>";
}
}
}
?>
</body>
</html>
</p>
Well, the way Google does it is a bit different. However, what you can do is use JavaScript (jQuery is probably easiest for you here) to send a XHR, which would retrieve the results. This would look something like this
$('input[name="question"]').on('keyup', function (e) {
$.ajax({
url: "search.php?go",
method: 'post',
data: {
query: e.target.val()
}
}).done(function(data) {
// Output your data however you want
});
}
Of course, you could also use the GET HTTP method, that's all your preference.
Now, aside from this, it looks like you have a SQL injection vulnerability in your query. Essentially, if I would input 'DROP DATABASE question as my search query, that would drop your database. What you should be doing is using prepared statements using Mysql::prepare, see the docs here.
Final note: Google does not do it this way. The best way to achieve blazing fast search results is using WebSockets to maintain a socket connection to your server, and letting the search run through a document database such as Elasticsearch, which is optimised for full-text search.
Step 1:
give ID to your input field...
<div class="content">
<input type="text" class="search" id="searchid" placeholder="Search Here" />
<div id="result"></div>
</div>
Step 2:
On keyUp search variable is cathed into vaiable and passed via AJAX to "findit.php"
<script type="text/javascript" src="jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(function(){
$(".search").keyup(function()
{
var searchid = $(this).val();
var dataString = \'search=\'+ searchid;
if(searchid!=\'\')
{
$.ajax({
type: "POST",
url: "findit.php",
data: dataString,
cache: false,
success: function(html)
{
$("#result").html(html).show();
}
});
}return false;
});
jQuery("#result").on("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find(\'.name\').html();
var decoded = $("<div/>").html($name).text();
$(\'#searchid\').val(decoded);
});
jQuery(document).live("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search")){
jQuery("#result").fadeOut();
}
});
$(\'#searchid\').click(function(){
jQuery("#result").fadeIn();
});
});
</script>
Step 3:
Now create a php file having name "findit.php" and use the below code
include('conn.php'); //this is your DB connection file
if($_POST)
{
$q = mysqli_real_escape_string($connection,$_POST['search']);
$qry = mysqli_query($connection,"select col_name from tbl_name where col_name like '%$q%' order by col_name LIMIT 7");
while($row=mysqli_fetch_array($qry))
{
$col_name = $row['col_name'];
$b_res = '<strong>'.$q.'</strong>';
$final_res = str_ireplace($q, $b_res, $col_name);
?>
<?php
}
}
?>
Related
So Im designing a searchfunction for the backend of a website and Im doing so with AJAX.
So far if you press the "Members" Button it gets the relevant info from the database and displays the members in a table. So far so good.
Now I added a form above the div in which it displays the table:
<form id="searchmember" method="post">
<input type="text" name="searchm" placeholder="Look for a Member!"/>
<input id="search" type="submit" value=">>" name="search"/>
</form>
<div id="eachTable">
And added a function into my JQuery that reacts when the "search" button gets pressed:
$("#search").click(function(){
if(ifIssetData == 1){
var searchm = $('input[name="searchm"]').val();
$.post('/website/administrator/components/com_backend/searchPerson.php', 'val=' + $(searchm).val());
$.ajax({
async: true,
dataType: 'json',
url: '/website/administrator/components/com_backend/searchPerson.php',
error: function(data2, error2, errorThrown2){
alert(JSON.stringify(data2));
alert(error2);
alert(errorThrown2);
},
success: function(data2,status)
{
createTableByJqueryEach2(data2);
},
});
The createTable function is designed to take the data, put it into a table and display that table in the eachTable Div.
So you see it posts searchm to the php file where the following happends:
<?php
include($_SERVER['DOCUMENT_ROOT'].'/website/dbConnection.php');
$searchtrue = $_POST['val'];
$query = "SELECT Titel, Vorname, Nachname, Unternehmen, Gruppe FROM mitglieder WHERE Titel LIKE '%$searchtrue%' OR Vorname LIKE '%$searchtrue%' OR Nachname LIKE '%$searchtrue%' OR Unternehmen LIKE '%$searchtrue%' OR Gruppe LIKE '%$searchtrue%'";
function filterTable($query)
{
$filter_Result = mysqli_query($GLOBALS['connect'], $query);
return $filter_Result;
}
$searchresult = filterTable($query) or die("Tabelle kann nicht angezeigt werden");
$data2 = mysqli_fetch_all($searchresult);
echo json_encode($data2);
?>
So now that you have the code, the Issue. When I press the "search" button the page just reloads and nothing happens. I assume the PHP File doesnt receive the POST? But why? The html is very simple so Im sure that works. The PHP should work but Im not sure since I always had a difficult time getting JQuery and PHP Files to work together.
Anybody know where my issue lies?
edit: I thought Ill just add the function in case the issue lies there
function createTableByJqueryEach2(data2)
{
var eTable2="<table><thead><tr><th colspan='5'>Created by for loop</th></tr><tr><th>Titel</th><th>Vorname</th><th>Name</th><th>Unternehmen</th><th>Gruppe</th</tr></thead><tbody>"
$.each(data2,function(index2, row2){
// eTable += "<tr>";
// eTable += "<td>"+(data2)[i]['Titel']+"</td>";
// eTable += "<td>"+(data2)[i]['Vorname']+"</td>";
// eTable += "<td>"+(data2)[i]['Name']+"</td>";
// eTable += "<td>"+(data2)[i]['Unternehmen']+"</td>";
// eTable += "<td>"+(data2)[i]['Gruppe']+"</td>";
// eTable += "</tr>";
eTable2 += "<tr>";
$.each(row2,function(key2,value2){
eTable2 += "<td>"+value2+"</td>";
});
eTable2 += "</tr>";
});
eTable2 +="</tbody></table>";
$('#eachTable').html(eTable2);
}
Your form is getting submitted as you have a submit input, and it has no action, so it's refresing.
You can change your form to a div or use this:
$(document).ready(function() {
$('#searchmember').on('submit', function(e){
e.preventDefault();
});
});
Also, I created this file and it's working nice:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form id="searchmember" method="post">
<input type="text" name="searchm" placeholder="Look for a Member!"/>
<input id="search" type="submit" value=">>" name="search"/>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#searchmember').on('submit', function(e){
e.preventDefault();
});
});
$("#search").click(function(e){
var ifIssetData= 1;
if(ifIssetData == 1){
var searchm = $('input[name="searchm"]').val();
$.post('/website/administrator/components/com_backend/searchPerson.php', 'val=' + $(searchm).val());
$.ajax({
async: true,
dataType: 'json',
url: '/website/administrator/components/com_backend/searchPerson.php',
error: function(data2, error2, errorThrown2){
alert(JSON.stringify(data2));
alert(error2);
alert(errorThrown2);
},
success: function(data2,status)
{
createTableByJqueryEach2(data2);
}
});
}
});
</script>
</body>
</html>
You don't need to use a form with AJAX.
If you replace the form with a div, it will resolve the problem.
When you "submit" the form, it tries to post the data somewhere.
Since you've not supplied a URL, it reloads.
I hava a dynamic list, loading from database in my php page.This list also have a delete button. When i click this button i need to get id of this button and delete from database that line with php code.
$dbh = new PDO("sqlite:database.sdb");
$sql ="SELECT * FROM clip";
foreach ($dbh->query($sql) as $row)
{
print 'Id: '. $row['id'] .'<br />';
echo '<input type="submit" id="'.$row['id'].'" value="delete" name="del">';
}
also this is my final code for button click;
$dbh->exec("delete clip where id='in here should be button id'");
How can i connect with this two code. Thanks already.
Given the level of your question I am assuming you are unfamiliar with jQuery and AJAX, but you should research both.
For a simple solution not using these you could do as follows:
Change the output to be <input type="button" id="'.$row['id'].'" value="Delete" onclick="do_delete(this.id)">;
Then you need a php script on the server side to handle the delete function, e.g. yourhandler.php
<?
//connect to DB here
if ($_POST['id']) {
$sql = "delete from clip where id=:delete_id";
$stmt = $dbh->prepare($sql);
$stmt->execute([':delete_id'=>$_POST['id']]);
}
?>
Then on the client side you need a form which submits when the button is clicked. Here is an example form code:
<form action="yourhandler.php" method="post" id="myform">
<!--Your PHP script which creates buttons-->
<input type="hidden" value="" name="id" id="delete_id">
</form>
<script>
function do_delete(which) {
var x = document.getElementById('delete_id');
x.value=which;
document.getElementById('myform').submit();
}
</script>
You can use this working jquery template for your task. It binds to all inputs that has a name="del".
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script>
$(document).ready(function() {
$('input[name="del"]').on('click', function() {
alert('button id is '+$(this).attr('id'));
var button_id = $(this).attr('id');
$.ajax({
method: 'post',
url: "delete.php",
data: {'did':button_id},
dataType: "html",
success: function(result) {
alert(result);
}
});
});
});
</script>
In your PHP delete file, you can retrieve the delete id via $_POST['did'].
This is index.php . when i give a input, it fetch the specific name and year. that's OK . but when i submit the form ,without any input it gives all the name of the movie and years but i don't want that ,the user can not show all the data saved in the database. i gave priventdefault() method but it's not working. how can i solve this problem ?
<!DOCTYPE html>
<html>
<head>
<title>ajax</title>
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
<script type="text/javascript">
$(function() // this function excited if the jquery is ready i mean after jquery successfully loaded
{
function loaddata()
{
var moviename= $("#moviename").val(); // read moviename value and assign;
$.ajax({
type: "GET",
url: "query.php",
data: {
name:moviename // there is no variable name so you have to assign the moveiname to name vairable ;
},
success: function (data) {
$("#result").html(data);
}
});
}
$("#submit").click(function(event) // Click Event Listener.
{
event.preventDefault();
loaddata()
});
});
</script>
</head>
<body>
<p>Enter movie name </p>
<form action="" method="POST">
<input type="text" name="moviename" id="moviename" placeholder="Enter Movie Name" required autocomplete="off">
<input type="submit" name="submit" id="submit" value="Search"/>
<!-- if you want ot use jquery you have to use event listener. like $("#submit").click(function(event){}); code from line 31 to 35 -->
</form>
<br>
<div id="result">
</div>
</body>
</html
///this is query.php
<?php
include 'dbcon.php';
$name =isset($_GET['name'])?$_GET['name']:'';
$query = mysqli_query( $conn,"SELECT * FROM movie WHERE name like '%$name%'");
while($row = mysqli_fetch_array($query))
{
echo "<p>".$row['name']."</p>";
echo "<p>".$row['year']."</p>";
}
?>
Execute the query only if $name is not null.
if(!empty($name)) {
$query = mysqli_query( $conn,"SELECT * FROM movie WHERE name like '%$name%'");
while($row = mysqli_fetch_array($query)){
echo "<p>".$row['name']."</p>";
echo "<p>".$row['year']."</p>";
}
}
$name =isset($_GET['name'])?$_GET['name']:'';
if(!empty($name)){
$query = mysqli_query( $conn,"SELECT * FROM movie WHERE name like '%$name%'");
while($row = mysqli_fetch_array($query))
{
echo "<p>".$row['name']."</p>";
echo "<p>".$row['year']."</p>";
}
}
in javascript
var moviename= $("#moviename").val(); // read moviename value and assign;
if(moviename){
$.ajax({
type: "GET",
url: "query.php",
data: {
name:moviename // there is no variable name so you have to assign the moveiname to name vairable ;
},
success: function (data) {
$("#result").html(data);
}
});
}
In query.php, you always assign empty string to $name in the line if empty 'name' value passed into query.php
$name =isset($_GET['name'])?$_GET['name']:'';.
So query will return you all the results in db as $name is an empty string and matches with all the data in db.
You can validate if $name is empty, not to run the query.
I'm new in bootstrap and i need some help please, i want to create a typeahead drop-down that return 3 values from my mysql database when the user search for a contact name in "ContactName" TEXTBOX and fill up 3 edit box with the information of
-contact name
-Telephone Number
-email address
thanks a lot on advance for all your effort
this is the code that i try it to return one value i need to modified to return all those tree value
Now when i try to search the contact name it will return with correctly with no question to ask but i don't know how to modify the code to bring 3 value like i mention above
enter code here
**php page: Customer.php**
-------------------------------------------
<?php
$host = "localhost";
$uname = "root";
$pass = "";
$database = "db34218";
$connection=mysql_connect($host,$uname,$pass) or die("connection in not ready <br>");
$result=mysql_select_db($database) or die("database cannot be selected <br>");
if (isset($_REQUEST['query'])) {
$query = $_REQUEST['query'];
$sql = mysql_query ("SELECT ContactName, Telephone, Email FROM customer WHERE ContactName LIKE '%{$query}%'");
$array = array();
while ($row = mysql_fetch_assoc($sql)) {
$array[] = $row['ContactName'];
}
echo json_encode ($array); //Return the JSON Array
}
?>
**html and java page and some php: Customersearch.php**
------------------------------------------------
<body>
.
.
.
<div class="row-fluid">
<div class="span4">
<label>ContactName </label>
<input type="text" name="ContactName" value="<?php echo $row_Recordset_QuoteCustomer['ContactName']?>" data-provide="typeahead" class="typeahead input-xlarge" autocomplete="off">
</div>
<div class="span2">
<label>Telephone </label>
<input type="text" name="Telephone" value="<?php echo htmlentities($row_Recordset_QuoteCustomer['Telephone'], ENT_COMPAT, 'utf-8'); ?>" class="span12">
</div>
<div class="span2">
<label>Email </label>
<input type="text" name="Email " value="<?php echo htmlentities(row_Recordset_QuoteCustomer['Email '], ENT_COMPAT, 'utf-8'); ?>" class="span12">
</div>
.........
.
.
.
.
.
.
<script src="../js/jquery.js"></script>
<script src="../js/bootstrap-transition.js"></script>
<script src="../js/bootstrap-alert.js"></script>
<script src="../js/bootstrap-modal.js"></script>
<script src="../js/bootstrap-dropdown.js"></script>
<script src="../js/bootstrap-scrollspy.js"></script>
<script src="../js/bootstrap-tab.js"></script>
<script src="../js/bootstrap-tooltip.js"></script>
<script src="../js/bootstrap-popover.js"></script>
<script src="../js/bootstrap-button.js"></script>
<script src="../js/bootstrap-typeahead.js"></script>
<script src="../js/SpecWorkPages/getItemsList.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('input.typeahead').typeahead({
source: function (query, process)
{
$.ajax(
{
url: 'Customer.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + query,
success: function(data)
{
console.log(data);
process(data);
}
});
}
});
})
</script>
</body>
</html>
<?php
mysql_free_result($RecordsetQuote);
mysql_free_result($Recordset_QuoteStatus);
mysql_free_result($Recordset_QuoteCustomer);
?>
If I'm understanding you correctly, you are getting results back but unable to populate the input fields. Although I don't use Twitter Bootstrap typeahead I do something very similar with jQuery's autocomplete feature. The code below is untested and of course you'll need to modify it for yourself but hopefully will be of some help.
See this working jsFiddle demo for something similar.
PHP
$array = array();
while ($row = mysql_fetch_assoc($sql)) {
array_push($array,array('ContactName'=>$row['ContactName'],'Telephone'=>$row['Telephone'],'Email'=>$row['Email']));
}
echo json_encode($array);
You can check what gets returned by manually entering the URL (ex: yoursite/Customer.php?query=SomeContactName). You should see something similar to this:
[{"ContactName":"Some Contact","Telephone":"5555555555","Email":"email#whatever.com"},
{"ContactName":"Some Other Contact","Telephone":"5555555555","Email":"anotheremail#whatever.com"}]
HTML/Javascript
<script>
$('input.typeahead').typeahead({
source: function (query, process) {
$.ajax({
url: 'Customer.php',
type: 'POST',
dataType: 'JSON',
// data: 'query=' + query,
data: 'query=' + $('#contactName').val(),
success: function(data)
{
var results = data.map(function(item) {
var someItem = { contactname: item.ContactName, telephone: item.Telephone, email: item.Email };
return JSON.stringify(someItem.contactname);
});
return process(results);
}
});
},
minLength: 1,
updater: function(item) {
// This may need some tweaks as it has not been tested
var obj = JSON.parse(item);
return item;
}
});
</script>
Here are a couple other posts that you might want to take a look at How to return the response from an AJAX call? and Bootstrap typeahead ajax result format - Example
I want to load data when page is loaded but if i try doing that then delete function doesn't work and whenever I insert the effect should be seen in table without refreshing page Please check my code what changes to be done in this
index.php
<script src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(e) {
$("#Submit").click(function(e) {
var name = $('#name').val();
var message=$('#message').val();
if($(":text").val().length==0)
{
$(":text").after('<span class="error">Field cannot be empty</span>');
$('#name').addClass('error');
$('#message').addClass('error');
return;
}
else{
$('#name').removeClass('error');
$('#message').removeClass('error');
//$('#propspectDiv').removeClass('error');
$('#propspectDiv').html('Submitting your Request.<img src="ajax.gif" />');
$.ajax({
url : 'data.php',
data:{
"name" : name,
"message" : message
},
success : function(data){
window.setTimeout(function(){
$('#propspectDiv').html('Your Name is added to our records');
$('#data').css("display","block");
$('#data').html(data);
}, 2000);
},
complete:function(){
$('#myform').each(function(){
this.reset();
});
}
});
}
});
$("a").click(function() {
$.post('delete.php',{ id: $(this).attr("id")});
});
});
</script>
</head>
<body>
<form id="myform">
<div id="wrapper">
Name : <input type="text" id="name" />
</br>
Message : <input type="text" name="message" id="message" />
</br>
<input type="button" value="Submit" id="Submit" />
<div id="propspectDiv"></div>
<table id="data" border="1" style="display:none;"></table>
</div>
</form>
</body>
data.php
<?php
$name = $_REQUEST['name'];
$message = $_REQUEST['message'];
include('connection.php');
$sql = "INSERT INTO login (username,message) VALUES ('$name','$message')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
$sqlnew = 'Select * from login order by id ASC';
$res = mysql_query($sqlnew);
echo'<tr>';
echo'<td>SrNo.</td>';
echo '<td>Name:</td>';
echo '<td>Message:</td>';
echo '<td>Delete</td>';
echo'</tr>';
$i=1;
while($row = mysql_fetch_array($res))
{
echo '<tr>';
echo'<td>'.$i.'</td>';
echo'<td>'.$row['username'].'</td>';
echo '<td>'.$row['message'].'</td>';
echo"<td id=td1>
<a href=delete.php?id=".$row['id']."&type=Delete>Delete</a></td>";
echo '</tr>';
$i++;
}
?>
delete.php
<?php
include('connection.php');
if(isset($_REQUEST["id"]))
{
$cmd=mysql_query("delete from login where id=" .$_REQUEST["id"] .";");
header("location: index.php");
}
?>
Looks like your grabbing the ID attribute of the link, but not setting it...
$("a").click(function() {
$.post('delete.php',{ id: $(this).attr("id")});
});
There is no ID attribute on your existing delete link:
<a href=delete.php?id=".$row['id']."&type=Delete>Delete</a></td>";
Also - you probably don't need to have the link href pointing to delete.php as its irrelevant when the jquery click event does all the work.
Also, because you are inserting the html (including the delete method) via jquery you may need to use the "on" event
I'm doing this off the cuff so the code may have some minor bugs but I believe this is the path you want to take...
Revised it might look like this:
JQUERY
$("a").on("click", function(e) {
e.preventDefault();
$.post('delete.php',{ id: $(this).attr("id")});
return false;
});
LINK
echo"<td id=td1>
<a id='".$row['id']."' href='#'>Delete</a>";
echo '</tr>';
couple things to note...
1 - above i'm not actually VERIFYING the record was deleted before I remove the appropriate table row - you may want to implement something to check this
2 - an alternative to removing the table row would be to just update the table in general by repulling the data and outputting it - if you know what i mean