I have a live search where it pulls all the relevant information from the database and displays it in the table relevant to the search using Ajax so it doesn't refresh the page, I have it so after each search it resets back to nothing until it receives another input but I want it to display what it normally does (all the information).
Before input is received: http://prntscr.com/hnmui8
After input is received: http://prntscr.com/hnmv0r
After input is removed: http://prntscr.com/hnmv53
What is want it to look like after inputs removed: http://prntscr.com/hnmvhr
index.php
<!DOCTYPE html>
<html>
<head>
<title>Webslesson Tutorial | Autocomplete Textbox using Bootstrap Typehead with Ajax PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
</head>
<body>
<br /><br />
<div class="container" style="width:600px;">
<h2 align="center">Ajax live data search using Jquery PHP MySql</h2>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">Search</span>
<input type="text" name="search_text" id="search_text" placeholder="Search by Customer Details" class="form-control" />
</div>
</div>
<br />
<div id="result">
<div class='table-responsive'>
<table class='table table-bordered'>
<tr>
<th>Customer name</th>
<th>Address</th>
<th>City</th>
<th>Potal code</th>
<th>Country</th>
</tr>
<?php
include('db.php');
$customers = DB::query('SELECT * FROM live');
foreach($customers as $p){
echo '<tr>
<td>'.$p["name"].'</td>
<td>'.$p["address"].'</td>
<td>'.$p["city"].'</td>
<td>'.$p["postCode"].'</td>
<td>'.$p["country"].'</td>
</tr>';
}
?>
</div>
</div>
</body>
</html>
<script>
$('#search_text').keyup(function(){
var txt = $(this).val();
if(txt != ''){
$.ajax({
url: "fetch.php",
method: "POST",
data:{search:txt},
dataType: "text",
success:function(data){
$('#result').html(data);
}
});
}else{
$('#result').html('');
});
</script>
fetch.php
<?php
$connect = mysqli_connect("localhost", "root", "", "ajax");
$output = '';
$sql = "SELECT * FROM live WHERE name LIKE '%".$_POST['search']."%'";
$result = mysqli_query($connect, $sql);
if(mysqli_num_rows($result) > 0){
$output .= "<h4 align='center'>Search result</h4>";
$output .= "<div class='table-responsive'>
<table class='table table-bordered'>
<tr>
<th>Customer name</th>
<th>Address</th>
<th>City</th>
<th>Potal code</th>
<th>Country</th>
</tr>";
while($row = mysqli_fetch_array($result)){
$output .= '
<tr>
<td>'.$row["name"].'</td>
<td>'.$row["address"].'</td>
<td>'.$row["city"].'</td>
<td>'.$row["postCode"].'</td>
<td>'.$row["country"].'</td>
</tr>
';
}
echo $output;
}else{
echo "There are no customers.";
}
?>
Thanks,
Ethan
You could save your original dataset into a variable and if the input is '', than instead of setting the html content to '', you could restore the content from the variable like so:
var originalData = $('#result').html();
$('#search_text').keyup(function(){
var txt = $(this).val();
if(txt != ''){
$.ajax({
url: "fetch.php",
method: "POST",
data:{search:txt},
dataType: "text",
success:function(data){
$('#result').html(data);
}
});
} else {
$('#result').html(originalData);
}
});
Last Update: I (lately) realized that your JS code already have an empty string check (thanks to #Taplar). #dferenc already posted correct answer for your case. But still if you want to be sure that your list is "fresh" you can follow my solution.
When you send an empty string to the server as a value of the parameter, it may be ommited. So, you should add a conditional check for that.
Use
$queryWord = isset($_POST['search']) ? $_POST['search'] : '';
$sql = "SELECT * FROM live WHERE name LIKE '%".$queryWord."%'";
or (after PHP7, you can use null coalescing operator)
$queryWord = $_POST['search'] ?? '';
$sql = "SELECT * FROM live WHERE name LIKE '%".$queryWord."%'";
instead of
$sql = "SELECT * FROM live WHERE name LIKE '%".$_POST['search']."%'";
Important Note: Beware of SQL Injections always! Protect your code against injections. You may start from
here.
Important Note 2: I suggest you to use "Developer Console" feature of browsers. All commonly-used browsers have inline-tool for
developers to debug, trace network requests and do some
magic.
Related
I got a small problem.
I want to look up the name by entering the website. Now, all records are displayed. What I want is that he shows it after something has been entered in the input. I don't want him to show everything immediately.
Here some code to know how it looks like.
FETCH.PHP
Get everything from database
if(isset($_POST["query"]))
{
$search = mysqli_real_escape_string($connect, $_POST["query"]);
$query = "
SELECT * FROM tbl_customer
WHERE website LIKE '%".$search."%'
OR naam LIKE '%".$search."%'
";
}
else
{
$query = "
SELECT * FROM test ORDER BY id
";
}
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
$output .= '
<div class="table-responsive">
<table class="table table bordered">
<tr>
<th>Website</th>
<th>Naam</th>
</tr>
';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["website"].'</td>
<td>'.$row["naam"].'</td>
</tr>
';
}
echo $output;
}
INDEX.PHP
<div class="container">
<br />
<h2 align="center">Ajax Live Data Search using Jquery PHP MySql</h2><br />
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">Search</span>
<input type="text" name="search_text" id="search_text" placeholder="Zoek door website" class="form-control" />
</div>
</div>
<br />
<div id="result"></div>
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#search_text').keyup(function(){
var search = $(this).val();
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
</script>
why do u call function load_data(); on load.
this might be the issue
also remove it from else condition
My goals is to make filter for loading posts from 1 week ago, 1 month ago and two inputs from date from and date to ( if one of them is empty to be filled with current date( y-m-d h:m:s ) format
This is all i tried and could have made it to work, every answer is much appreciated, thank you
Tl:dr
Select filter for week ago, month ago
From date - to date ( if one of those is empty then use current date )
Index.php
<?php
$connect = mysqli_connect("localhost", "root", "", "testing");
$query = "SELECT * FROM tbl_order ORDER BY order_id desc";
$result = mysqli_query($connect, $query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Webslesson Tutorial | Ajax PHP MySQL Date Range Search using jQuery DatePicker</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
</head>
<body>
<br /><br />
<div class="container" style="width:900px;">
<h2 align="center">Ajax PHP MySQL Date Range Search using jQuery DatePicker</h2>
<h3 align="center">Order Data</h3><br />
<div class="col-md-3">
<input type="text" name="from_date" id="from_date" class="form-control" placeholder="From Date" />
</div>
<div class="col-md-3">
<input type="text" name="to_date" id="to_date" class="form-control" placeholder="To Date" />
</div>
<div class="col-md-5">
<input type="button" name="filter" id="filter" value="Filter" class="btn btn-info" />
</div>
<div style="clear:both"></div>
<br />
<div id="order_table">
<table class="table table-bordered">
<tr>
<th width="5%">ID</th>
<th width="30%">Customer Name</th>
<th width="43%">Item</th>
<th width="10%">Value</th>
<th width="12%">Order Date</th>
</tr>
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td><?php echo $row["order_id"]; ?></td>
<td><?php echo $row["order_customer_name"]; ?></td>
<td><?php echo $row["order_item"]; ?></td>
<td>$ <?php echo $row["order_value"]; ?></td>
<td><?php echo $row["order_date"]; ?></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$(function(){
$("#from_date").datepicker();
$("#to_date").datepicker();
});
$('#filter').click(function(){
var from_date = $('#from_date').val();
var to_date = $('#to_date').val();
if(from_date != '' && to_date != '')
{
$.ajax({
url:"filter.php",
method:"POST",
data:{from_date:from_date, to_date:to_date},
success:function(data)
{
$('#order_table').html(data);
}
});
}
else
{
alert("Please Select Date");
}
});
});
</script>
And filter.php
<?php
//filter.php
if(isset($_POST["from_date"], $_POST["to_date"]))
{
$connect = mysqli_connect("localhost", "root", "", "testing");
$output = '';
$query = "
SELECT * FROM tbl_order
WHERE order_date BETWEEN '".$_POST["from_date"]."' AND '".$_POST["to_date"]."'
";
$result = mysqli_query($connect, $query);
$output .= '
<table class="table table-bordered">
<tr>
<th width="5%">ID</th>
<th width="30%">Customer Name</th>
<th width="43%">Item</th>
<th width="10%">Value</th>
<th width="12%">Order Date</th>
</tr>
';
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'. $row["order_id"] .'</td>
<td>'. $row["order_customer_name"] .'</td>
<td>'. $row["order_item"] .'</td>
<td>$ '. $row["order_value"] .'</td>
<td>'. $row["order_date"] .'</td>
</tr>
';
}
}
else
{
$output .= '
<tr>
<td colspan="5">No Order Found</td>
</tr>
';
}
$output .= '</table>';
echo $output;
}
?>
Use something like this to make sure that you are getting the correct format from your datepicker:
$("#from_date").datepicker({ dateFormat: 'yy-mm-dd' }).val();
Make PHP variables to use in your query for the date:
$fromDate = !empty($_POST['from_date']) ? "'".mysqli_escape_string($_POST["from_date"])."'" : "CURDATE()";
$toDate = !empty($_POST["to_date"]) ? "'".mysqli_escape_string($_POST["to_date"])."'" : "CURDATE()";
$query =
"SELECT *
FROM tbl_order
WHERE order_date
BETWEEN $fromDate
AND $toDate";
NOTE: You should also add some logic in there to make sure that the from_date does not end up being before the to_date.
NOTE 2: This answer is making the assumption that you have not set up PDO. Always make sure to avoid SQL injection attacks in some way. Any values coming from the front end are unsafe and subject to SQL injection. PDO would be preferable, but escaping will work.
You can try casting your $_POST using CAST function to convert values to date.
$query = "SELECT * FROM tbl_order
WHERE order_date
BETWEEN CAST('".$_POST["from_date"]."' AS DATE)
AND CAST('".$_POST["to_date"]."' AS DATE)";
You can read about it on MySQLTutorial .
Also I recommend you to escape variables when working with database :-) Always expect user is up to no good.
I am trying to create a search within my table.
I have the table populated with date already loaded, but when i type into the search box for example a name and press submit, nothing is happening the page just reloads and nothing happens.
Here is the code, (i also need to do the same with a table where the table data is all foreign keys.)
<?php // Include config file
include("$_SERVER[DOCUMENT_ROOT]/freddies/inc/config.php");
include("$_SERVER[DOCUMENT_ROOT]/freddies/inc/functions.php");
include("$_SERVER[DOCUMENT_ROOT]/freddies/inc/header.php");
$sql = "SELECT * FROM patient";
if (isset($_POST['searchform'])) {
$search_term = ($_POST['searchpat']);
$sql .= " WHERE fName LIKE '{$search_term}'";
$sql .= " OR sName LIKE '{$search_term}'";
$sql .= " OR addLineOne LIKE '{$search_term}'";
}
$query = mysqli_query($db, $sql) or die(mysql_error());
?>
<body>
<div class="container">
<?php include("$_SERVER[DOCUMENT_ROOT]/freddies/inc/logo.html"); ?>
<h2>List of Patients</h2>
<p>All Patients Registered with Freddies Medical:</p>
<form name="searchform" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<div class="form-group">
<label>Search for Patient</label>
<input type="text" class="form-control" name="searchpat" required><br>
<input type="submit" class="btn btn-primary" name="search" value="Submit">
<span class="help-block"></span>
</div>
<table class="table table-striped">
<thead>
<tr>
<th>First Name</th>
<th>Surname</th>
<th>Address</th>
<th>Phone</th>
<th>Email Address</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
$no = 1;
$total = 0;
while ($row = mysqli_fetch_array($query))
{
echo '<tr>
<td>'.$row['fName'].'</td>
<td>'.$row['sName'].'</td>
<td>'.$row['addLineOne'].", ".$row['addCity'].", ".$row['addPostCode'].'</td>
<td>'.$row['phone'].'</td>
<td>'.$row['email'].'</td>
<td>View Patient</td>
<td>Delete</td>
</tr>';
$no++;
}?>
</tbody>
</table>
New Patient
Admin Area
</div>
<div class="bottompadding"></div>
<?php include("$_SERVER[DOCUMENT_ROOT]/freddies/inc/footer.php"); ?>
</body>
</html>
$_POST['searchform'] will not be set as far as I know since it is the name of the form and not a form element. Better check for isset($_POST['search']):
if(isset($_POST['search'])) {
$search_term = $_POST['searchpat'];
$sql .= " WHERE fName LIKE '%".$search_term."%'"; // Using % wildcard will search for fields 'containing' searched string rather then 'exact matches'
$sql .= " OR sName LIKE '%".$search_term."%'";
$sql .= " OR addLineOne LIKE '%".$search_term."%'";
}
I have to display the all the records on the screen which are inserted into the database without refreshing the page. I have 3 columns called as Firstname, Lastname, Email and after clicking on the submit button data are inserting in the database using ajax Which is working.
Now I am fetching the records on the same screen without refresh the page but it is not working when I am refreshing the page then it is displaying the last record which is inserted.
Please check below link. You will get an idea what I am asking. Inserted data and display data at the same time.
http://prntscr.com/g953bs
Index.php
<?php
ob_start();
session_start();
include('../../db/connection.php');
$sql = "SELECT * FROM test1";
$result = $conn->query($sql);
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form method="post" id="register" autocomplete="off">
<input type="text" name="fname" id="fname" placeholder="Firstname">
<input type="text" name="lname" id="lname" placeholder="Lastname">
<input type="email" name="email" id="email" placeholder="Email">
<input type="submit" name="submit" value="submit" >
</form>
<table border="1" style="margin-top: 25px;">
<tr>
<th>Id</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>".$row['id']."</td>
<td>".$row['fname']."</td>
<td>".$row['lname']."</td>
<td>".$row['email']."</td>
</tr>";
}
} else {
echo "0 results";
}
$conn->close();
?>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$('#register').submit(function(e){
e.preventDefault(); // Prevent Default Submission
var fname = $("#fname").val();
var lname = $("#lname").val();
var email = $("#email").val();
var dataString = 'fname='+ fname + '&lname='+ lname + '&email='+ email;
$.ajax(
{
url:'process.php',
type:'POST',
data:dataString,
success:function(data)
{
// $("#table-container").html(data);
$("#register")[0].reset();
},
});
});
</script>
</body>
</html>
Process.php
$firstname=$_POST['fname'];
$lastname=$_POST['lname'];
$email=$_POST['email'];
$sql = "INSERT INTO test1 (fname, lname, email) VALUES ('$firstname', '$lastname', '$email')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
$conn->close();
$('#IdTable tr:last').after('<tr><td>id<td>fname<td>lname<td>email</tr>');
Define id to the table
<table border="1" style="margin-top: 25px;" id="myTable">
Changes in ajax call
$.ajax(
{
url:'process.php',
type:'POST',
data:dataString,
success:function(data)
{
$('#myTable tr:last').after('<tr><td>' +fname +'</td><td>'+lname+'</td><td>'+email+'</td></tr>');
$("#register")[0].reset();
},
});
Note: Also you should handle the case if eror while inserting in your code as currently you are only taking positive case.
I hope this will help
First of all I'd like to suggest taking a look at binding parameters with mysqli to make your query saver.
Then in order to add the date without refreshing you could return the data on successful insert. Then append this data to the table.
Example Process.php
if (mysqli_query($conn, $sql)) {
echo "<tr>
<td>".mysqli_insert_id($conn)."</td>
<td>".$firstname."</td>
<td>".$lastname."</td>
<td>".$email."</td>
</tr>";
} else {
As you have only one table then use below code.
$('table tr:last').after('<tr>...</tr><tr>...</tr>');
If you have any class or id then you can modify below syntax as $('selector tr:last')
Use it in success of ajax call
I have a scenario where on page load, a div is on display: none; and when i press button-A it toggles the div. This div acts as a search div window where end users can do search against database. But since the div is on display: none; when i submit a form on the search div window, it reloads the page and goes back to default where search div window is on display: none;
So, the data call actually executes and returns the rows i need. But I need to press the button-A again just to show the div that contains the results.
is there a workaround for this? i've read a little about ajax but i haven't really found a working solution for my case.
i have something like this. (sorry for not knowing good format on posting. its my first time to post here.)
<button id="hideshow" class="hideshow" type="submit">search</button>
<div class="search_div_wrapper" style="display: none;">
<form action="" method="POST">
<input type="text" name="search_field">
<button name="search" id="submit">search</button>
</form>
<?php
// some codes are here to query and display rows from search_field input
?>
</div>
<script>
jQuery(document).ready(function(){
jQuery('.hideshow').on('click', function(event) {
jQuery('#search_div_window').toggle('show');
});
});
</script>
$(function(){
$(".search").keyup(function()
{
var searchid = $(this).val();
var dataString = \'search=\'+ searchid;
if(searchid!=\'\')
{
$.ajax({
type: "POST",
url: "search.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();
});
});
<div class="form-group">
<input type="text" placeholder="search by name" name="search_text" class="form-control search" id="search_text"></div>
<div id="result"></div>
<!-- search.php--->
<?php
$conn = mysqli_connect("localhost", "root", "", "insert");
$output = "";
$sql = "SELECT * FROM inserdata WHERE name LIKE '%".$_POST['search']."%'";
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result) > 0)
{
$output .= '<h4 align="center">Search Result</h4>';
$output .= '<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone Number</th>
<th>Address</th>
<th>Gender</th>
<th>Desc</th>
</tr>';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["name"].'</td>
<td>'.$row["email"].'</td>
<td>'.$row["phn"].'</td>
<td>'.$row["address"].'</td>
<td>'.$row["gender"].'</td>
<td>'.$row["desc"].'</td>
</tr>
';
}
echo $output;
}
else {
echo "data not found";
}
?>
you can check if there is any result after loading. and show the search_div_wrapper if there is any
var $ = jQuery;
$(window).load(function(){
if($('.result_div_wrapper').html().trim().length > 0) {
console.log($('.result_div_wrapper').html().trim().length)
$('.result_div_wrapper').toggleClass('active');
}
});
and add this to your css
.active{
display: block !important;
}
.result_div_wrapper{
display: none;
}