I have the following php script which works fine, it uses the search term and compares it with a few different fields, then prints out the each record that matches:
<?php
mysql_connect ("localhost", "root","") or die (mysql_error());
mysql_select_db ("table");
$search = isset($_POST['search']) ? $_POST['search'] : '';
$sql = mysql_query("select * from asset where
name like '%$search%' or
barcode like '%$search%' or
serial like '%$search%' ");
while ($row = mysql_fetch_array($sql)){
echo '<br/> Name: '.$row['name'];
echo '<br/> Barcode: '.$row['barcode'];
echo '<br/> Serial: '.$row['serial'];
}
?>
And this is the form that links to it:
<form action="http://localhost/test/search.php" method="post">
Search: <input type="text" name="search" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
I need to some how encode the results of the search so I can use them in a javascript function, then I can display them on the same html page below the form.
For that you have to use AJAX. You can send data back to the same page using JSON.
Advice - Don't use mysql_* functions since they are deprecated. Learn mysqli_* and try using that.
<script>
$(function(ev){
ev.preventDefault();
$("form").on('submit', function(){
var form = $(this);
var url = form.attr('action');
var data = form.serialize();
$.post(url, data)
.done(function(response){
if(response.success == TRUE)
{
// Search result found from json
// You have to loop through response.data to display it in your page
// Your single loop will have something like below -
var name = response.data.name;
var barcode = response.data.barcode;
var serial = response.data.serial;
$("#name").html(name);
$("#barcode").html(barcode);
$("#serial").html(serial);
}
else
{
// search result not found
}
});
});
});
</script>
On search.php
<?php
mysql_connect ("localhost", "root","") or die (mysql_error());
mysql_select_db ("table");
$search = isset($_POST['search']) ? $_POST['search'] : '';
$sql = mysql_query("select * from asset where
name like '%$search%' or
barcode like '%$search%' or
serial like '%$search%' ");
$num = mysql_rows_nums($sql);
$json = array();
if($num > 0)
{
$json['success'] = TRUE;
while ($row = mysql_fetch_array($sql)){
$json['data']['name'] = $row['name'];
$json['data']['barcode'] = $row['barcode'];
$json['data']['serial'] = $row['serial'];
}
}
else
{
$json['success'] = FALSE;
}
return json_encode($json);
?>
Related
Having trouble pulling variables from one PHP to another script.
I have three different files, adminPage.html, reportScript.php, and report.php.
adminPage.html takes variables from the user and uses AJAX post function to post the variables to reportScript.php.
report.php is supposed to pull those posted variables from reportScript.php and use the variables in a SQL function, however, I am receiving an error stating that I have an "undefined index: startDate" and "undefined index: endDate" where I am instantiating the variables in PHP.
adminPage.html:
<center><h2> Choose the dates below that you need an order list from: </h2>
</br>
<form>
<h2>Start:</h2>
<input type="date" id ="reportStartDate" name = "startDate">
</br>
<h2>End:</h2>
<input type="date" id ="reportEndDate" name = "endDate">
</form>
</center>
</br></br>
<button id="runReportButton" onclick = "runReport()"> Run Report </button>
<script>
function runReport()
{
var jStartDate;
var jEndDate;
jStartDate = document.getElementById("reportStartDate").value;
jEndDate = document.getElementById("reportEndDate").value;
/*console.log(jStartDate);
console.log(jEndDate); */
$.ajax
({
type: "POST",
url: "phpScripts/reportScript.php",
data: {startDate: jStartDate, endDate: jEndDate},
success: function(response)
{
console.log("posted");
window.open("report.php", "_self");
}
});
}
</script>
reportScript.php:
<?php
require 'connect.php';
//posts data to db
$startDate = $_POST["startDate"];
$endDate = $_POST["endDate"];
$sql = "SELECT * FROM orderlist WHERE NOT (dateOrdered < startDate OR
dateOrdered > endDate)";
$result = $conn->query($sql);
if($result){
echo "true";
}
else{
echo "false";
}
?>
report.php:
<?php
require 'phpScripts/connect.php';
require 'phpScripts/reportScript.php';
//posts data to db
/*$startDate = $_POST['startDate'];
$endDate = $_POST['endDate'];*/
/*$startDate = '2018-01-01';
$endDate = '2018-08-08'; */
$sql = "SELECT * FROM orderlist WHERE NOT (dateOrdered < '$startDate' OR dateOrdered > '$endDate');";
$result = $conn->query($sql);
//above is reportScript.php, below is pulling list method from order.php
//below works, just needs variables from the reportScript
echo "<ul>";
if($result->num_rows >0)
{
$i = 0;
while($row = $result->fetch_assoc()) // this loads database into list, also
creates array of pricing which someone can pull from later to get total
{
echo "<li style='font-size:15px'>".$row["drinkName"]. ", Date Ordered: "
.$row["dateOrdered"] . ",Cost: " .$row["drinkCost"] . "</li>";
echo "</br>";
$i = $i+1;
}
}else {
echo "<p> you're a dummy and you did this wrong </p>";
}
echo "</ol>";
?>
You forgot the dollar sign ($) in your variables in reportScript.php.
$sql = "SELECT * FROM orderlist WHERE NOT (dateOrdered < $startDate OR
dateOrdered > $endDate)";
This statement is also vulnerable to sql injection.
With some of the advice taken from #Ralf, I combined both reportScript.php and report.php, and used a $_GET statement to put the date variables into the URL upon opening. This way, the query isn't placed twice and the variables are still saved.
I want to do text autocomplete using php and html..
i have tried the below code
<?php
$connection = mysqli_connect("localhost", "root", "pass", "data") or die("Error " . mysqli_error($connection));
$sql = "select value from fin";
$result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));
$dna = array();
while ($row = mysqli_fetch_array($result))
{
$dna[] = $row['value'];
}
$jj = array_unique($dna);
print_r(array_values($jj));
?>
result is
my html
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/
themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.4
/jquery-ui.js">
</script>
</head>
<body>
<form name="vinform" method="get"> <input type="text" name="editor" autocomplete="on"> <input type="submit" value="Show" id="display"> </form>
<div id="div1"></div>
<script type="text/javascript">
$(function() {
$('#div1').autocomplete({
source: "auto.php"
});
});
</script>
</body>
it doesn't show the words from mysql when i type some word in the text field ..i have to show the related words from mysql based on the text field input,when i type a character in the text field..can anyone help me to solve the issue in my code?
tried with Ajax
var se = null;
$(function () {
var minlength = 1;
$("#editor").keyup(function () {
var that = this,
value = $(this).val();
if (value.length >= minlength ) {
if (se != null)
se.abort();
se = $.ajax({
type: "GET",
url: "auto.php",
data: value,
dataType: "text",
success: function(msg){
if (value==$(that).val()) {
}
}
});
}
});
});
php
<?php
if(isset($_GET['editor']))
{
$con=mysqli_connect("localhost","root","admin321","data");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$name=$_GET['editor'];
$sql = "select value from fin where value LIKE '%".$name."'";
$result = mysqli_query($connection, $sql) or
die("Error " . mysqli_error($connection));
$dna = array();
while($row = mysqli_fetch_array($result))
{
$dna[] = $row['value'];
}
$jj=array_unique($dna);
print_r ( $jj);
}
?>
no autocomplete action
With option 1 (Jquery UI autocomplete) and try something like that
<?php
$connection = mysqli_connect("localhost", "root", "pass", "data") or die("Error " . mysqli_error($connection));
$sql = "select value from fin";
$result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));
$dna = array();
while ($row = mysqli_fetch_array($result))
{
$dna[] = $row['value'];
}
echo json_encode($dna);
?>
Jquery UI autocomplete state about source option
String: When a string is used, the Autocomplete plugin expects that string to point to a URL resource that will return JSON data. It can be on the same host or on a different one (must provide JSONP). The Autocomplete plugin does not filter the results, instead a query string is added with a term field, which the server-side script should use for filtering the results. For example, if the source option is set to "http://example.com" and the user types foo, a GET request would be made to http://example.com?term=foo. The data itself can be in the same format as the local data described above.
You can use AJAX and Jquery..in html code call the function on keyup event and send data using ajax request after that get data from database using LIKE query and display it..
in input add id="editor"
<input type="text" id="editor" name="editor" autocomplete="on">
I want Ajax to apply only in the div (#usersDiv)
When selector is changed into 'body' it loads the whole page repeatedly. (Cannot type in the box)
but when selector changed as #userDiv, it shows the search box twice in the page. In the first box can be typed, but again second box loads over and over.
PHP file is as follows (test.php)
<?php
$connection = mysqli_connect('localhost', 'root', '', 'users');
function users($connection){
if(!empty($_POST)){
$country = $_POST['userCountry'];
$sql = "SELECT * FROM users WHERE country = '$country' ";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$userName = $row['username'];
$city = $row['city'];
echo '<div><h4>'. $userName. " ". $city. '</h4></div>';
}
} else {
echo "Use search box!";
}
} else {
echo "Use Search Box!";
}
}
?>
<html>
<head><script src = "jquery.min.js"></script>
<script>
$(document).ready(function(){
$.getJSON("http://freegeoip.net/json/", function(data) {
var country = data.country_name;
$.ajax({
method:"POST",
url:"test.php",
data:{userCountry:country},
success:function(result){
$('#usersDiv').html(result);
}
});
});
});
</script>
</head>
<body>
<form name = "searchForm" action = "search.php" method = "POST">
<input type = "text" name = "searchPlace" required />
<input type = "submit" value = "Search"/>
</form>
<div id = "usersDiv"> <?php users($connection); ?> </div>
</body>
<html/>
I have altered your code to wrap your PHP function within an if($_POST) to prevent the entire page loading
<?php
$connection = mysqli_connect('localhost', 'root', '', 'users');
if($_POST){ // Check if form has been submitted
$country = $_POST['userCountry'];
$sql = "SELECT * FROM users WHERE country = '$country' ";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$userName = $row['username'];
$city = $row['city'];
echo '<div><h4>'. $userName. " ". $city. '</h4></div>';
}
} else {
echo "Use search box!";
}
}else{ // If it hasn't then show the search form
?>
<html>
<head><script src = "jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#searchForm").on("submit",function(e){ // Check for form submission
$.getJSON("http://freegeoip.net/json/", function(data) {
var country = data.country_name;
$.ajax({
method:"POST",
url:"test.php",
data:{userCountry:country},
success:function(result){
$('#usersDiv').html(result);
}
});
});
});
});
</script>
</head>
<body>
<form name = "searchForm" action = "search.php" method = "POST" id="searchForm">
<input type = "text" name = "searchPlace" required />
<input type = "submit" value = "Search"/>
</form>
<div id = "usersDiv"></div>
</body>
<html/>
<?php } ?>
As Alexander suggests, read up on SQL Injection
How can I prevent SQL injection
I'm trying to send two values from a form to another PHP using ajax post method. One value is the value that's already entered in an input box, and the other is a value that is being typed into another input box. It acts like a search box. I tried executing the SQL query in my SQL workbench and it returns the value properly. What am I doing wrong in my code?
function searchq6(){
var searchstate = $("input[name='region']").val();
var searchTxt = $("input[name='suburb']").val();
$.post("search-suburb.php", {searchVal: searchTxt, st:searchstate},function(sbb){
$("#sbb").html(sbb);
//searchq7();
});
}
This is the input box where I search and get the value from:
<input type="text" name="region" list="state" value="<?php echo $region; ?>" placeholder="Select State" id="output">
Suburb:
<input type="text" name="suburb" list="sbb" value="<?php echo $suburb; ?>" onkeyup="searchq6()" id="output">
<datalist id="sbb" name="taskoption6" >
<option> </option>
</datalist>
This is the search-suburb.php file:
$output = '' ;
if (isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
$st = $_POST['st'];
$query = mysqli_query($link, "SELECT DISTINCT title FROM `wp_locations` WHERE state="'.$st.'" AND `title` LIKE '%".$searchq."%' ")or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<option>No results!</option>';
}else{
while($row = mysqli_fetch_array($query)){
$suburb = $row['title'];
?>
<option value="<?php echo $suburb; ?>"><?php echo $suburb; ?> </option>
<?php
} // while
} // else
} // main if
<input type="text" name="region" list="state" value="<?=(isset($_POST['region'])?$_POST['region']:'');?>" placeholder="Select State" id="output">
Suburb:
<input type="text" name="suburb" onkeyup="searchq6()" list="sbb" value="<?=(isset($_POST['suburb'])?$_POST['suburb']:'');?>" onkeyup="searchq6()" id="output">
<datalist id="sbb" name="taskoption6"></datalist>
Javascript:
function searchq6(){
var searchstate = $("input[name='region']").val();
var searchTxt = $("input[name='suburb']").val();
$.post("search-suburb.php", {searchVal: searchTxt, st:searchstate},function(sbb){
var decode = jQuery.parseJSON(sbb); // parse the json returned array
var str = ""; // initialize a stringbuilder
$.each(decode, function (x, y) {
str+="<option value='" + y.title +"'>";
});
$("#sbb").html(str);
}); // end of post
}// end of searchq6 function
Php:
$output = '' ;
if (isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
$st = $_POST['st'];
$query = mysqli_query($link, "SELECT DISTINCT title FROM `wp_locations` WHERE state='{$st}' AND `title` LIKE '%{$searchq}%' ")or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<option>No results!</option>';
} else{
$data = array();
while($row = mysqli_fetch_array($query))
$data[] = $row;
echo json_encode($data);
}
} // main if
Got the answer from small snippets gathered through the comments
Changed the query to:
$query = mysqli_query($link, "SELECT DISTINCT title FROM `wp_locations` WHERE state='".$st."' AND `title` LIKE '%".$searchq."%' LIMIT 10")or die("Could not search!");
And the ajax to:
function searchq6(){
var searchstate = $("input[name='region']").val();
var searchTxt = $("input[name='suburb']").val();
$.post("search-suburb.php", {searchVal: searchTxt, st:searchstate})
.done(function(sbb) {
$("#sbb").html(sbb);
});
//searchq7();
}
Thanks for all the comments guys
I have a Ajax PHP Show More feature like youtube and Live search scripts but I can't get them to work together. For example my live search works but then the show more feature doesn't work with it on the search results and when I use the show more then the live search doesn't work.
They don't seem to be messing with each other. Can anyone help me out? I am new to this website so I will try my best to show my code and explain it.
INDEX.PHP
<?php
include_once("connect.php");
$sql = "SELECT COUNT(*) FROM database";
$query = mysqli_query($connect,$sql) or die (mysqli_error());
$item_per_page = 3;
$total_rows = mysqli_fetch_array($query);
$pages = ceil($total_rows[0]/$item_per_page);
?>
<!DOCTYPE html>
<head>
<script type="text/javascript">
// Show More Scripted
$(document).ready(function() {
var track_click = 0;
var total_pages = <?php echo $pages; ?>;
$('#news-table-wrap').load("showmore_search.php", {'page':track_click}, function() {track_click++;});
$(".load_more").click(function (e){
$(this).hide();
$('.animation_image').show();
if(track_click <= total_pages){
$.post(showmore_search.php',{'page': track_click}, function(data) {
$(".load_more").show();
$("#news-table-wrap").append(data);
$("html, body").animate({scrollTop: $("#load_more_button").offset().top}, 500);
$('.animation_image').hide();
track_click++;
}).fail(function(xhr, ajaxOptions, thrownError){
alert(thrownError);
$(".load_more").show();
$('.animation_image').hide();
});
if(track_click >= total_pages-1){
$(".load_more").attr("disabled", "disabled");
}
}
});
});
// Live Search Script
function searchNews(value) {
$.post("showmore_search.php", {newsResult:value}, function(data){
$("#news-table-wrap").html(data);
});
}
</script>
</head>
<body>
<input type="text" name="search" id="search" class="search-box" onKeyUp="searchNews(this.value)" placeholder="Search News">
<table id="news-table-wrap" class="news-table-wrap" cellpadding="0" cellspacing="0">
</table>
<div align="center">
<div class="load_more" id="load_more_button">Show More</div>
<div class="animation_image" style="display:none;"><img src="/files/ajax-loader.gif"></div>
</div>
</body>
</html>
SHOWMORE_SEARCH.php
<?php
include_once("connect.php");
$newsResult = $_POST['newsResult'];
$item_per_page = 3;
$page_number = $_POST["page"];
$position = ($page_number * $item_per_page);
$sql = "SELECT * FROM database WHERE headline LIKE '%$newsResult%' OR post LIKE '%$newsResult%' ORDER BY date DESC LIMIT $position, $item_per_page";
$query = mysqli_query($connect,$sql) or die (mysqli_error());
while ($row = mysqli_fetch_array($query)){
$headline = $row['headline'];
$author = $row['author'];
$date = $row['date'];
$post = $row['post'];
$name = $row['name'];
echo "<tr class='news-preview-wrap'>";
echo "<td><div class='news-preview-content'><div class='news-preview-headline'><a href='news_post?name=".$name."'>".$headline."</a></div>
<div class='news-preview-date'>Written by ".$author." on ".$date."</div>
<div class='news-preview-post'>".$post."</div></div>
<div class='news-more'><a href='news_post?name=".$name."'>Read More</a></div></td>";
echo "</tr>";
} else {
echo "<div class='search-error'>No search results were found...</div>";
}
?>
Here is something you can do with Ajax, PHP and JQuery. Hope this helps or gives you a start.
See live demo and source code here.
http://purpledesign.in/blog/to-create-a-live-search-like-google/
Create a search box, may be an input field like this.
<input type="text" id="search" autocomplete="off">
Now we need listen to whatever the user types on the text area. For this we will use the jquery live() and the keyup event. On every keyup we have a jquery function “search” that will run a php script.
Suppose we have the html like this. We have an input field and a list to display the results.
<div class="icon"></div>
<input type="text" id="search" autocomplete="off">
<ul id="results"></ul>
We have a Jquery script that will listen to the keyup event on the input field and if it is not empty it will invoke the search() function. The search() function will run the php script and display the result on the same page using AJAX.
Here is the JQuery.
$(document).ready(function() {
// Icon Click Focus
$('div.icon').click(function(){
$('input#search').focus();
});
//Listen for the event
$("input#search").live("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search_st.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}return false;
}
})
;
In the php, shoot a query to the mysql database. The php will return the results that will be put into the html using AJAX. Here the result is put into a html list.
Suppose there is a dummy database containing two tables animals and bird with two similar column names ‘type’ and ‘desc’.
//search.php
// Credentials
$dbhost = "localhost";
$dbname = "live";
$dbuser = "root";
$dbpass = "";
// Connection
global $tutorial_db;
$tutorial_db = new mysqli();
$tutorial_db->connect($dbhost, $dbuser, $dbpass, $dbname);
$tutorial_db->set_charset("utf8");
// Check Connection
if ($tutorial_db->connect_errno) {
printf("Connect failed: %s\n", $tutorial_db->connect_error);
exit();
}
$html = '';
$html .= '<li class="result">';
$html .= '<a target="_blank" href="urlString">';
$html .= '<h3>nameString</h3>';
$html .= '<h4>functionString</h4>';
$html .= '</a>';
$html .= '</li>';
$search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
$search_string = $tutorial_db->real_escape_string($search_string);
// Check Length More Than One Character
if (strlen($search_string) >= 1 && $search_string !== ' ') {
// Build Query
$query = "SELECT *
FROM animals
WHERE type LIKE '%".$search_string."%'
UNION ALL SELECT *
FROM birf
WHERE type LIKE '%".$search_string."%'"
;
$result = $tutorial_db->query($query);
while($results = $result->fetch_array()) {
$result_array[] = $results;
}
// Check If We Have Results
if (isset($result_array)) {
foreach ($result_array as $result) {
// Format Output Strings And Hightlight Matches
$display_function = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['desc']);
$display_name = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['type']);
$display_url = 'https://www.google.com/search?q='.urlencode($result['type']).'&ie=utf-8&oe=utf-8';
// Insert Name
$output = str_replace('nameString', $display_name, $html);
// Insert Function
$output = str_replace('functionString', $display_function, $output);
// Insert URL
$output = str_replace('urlString', $display_url, $output);
// Output
echo($output);
}
}else{
// Format No Results Output
$output = str_replace('urlString', 'javascript:void(0);', $html);
$output = str_replace('nameString', '<b>No Results Found.</b>', $output);
$output = str_replace('functionString', 'Sorry :(', $output);
// Output
echo($output);
}
}