So I have a working ajax/jquery dropdown/list that populates results from the database depending on the users input.
Basically is populates a <li> for every resu1lt in the database, and makes it into a link that can then go to that persons profile page.
I have tested the code and it works perfectly on the test page, but as soon as it has other content behind it, the links don't work anymore. How can I fix this?
here is the code:
custom.js:
/* JS File */
// Start Ready
$(document).ready(function() {
// Icon Click Focus
$('div.icon').click(function(){
$('input#search').focus();
});
// 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.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}return false;
}
$("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));
};
});
});
search.php (the file that searches, not the page that is displayed to the user):
/************************************************
Search Functionality
************************************************/
// Define Output HTML Formating
$html = '';
$html .= '<li class="result">';
$html .= '<a target="_blank" href="urlString">';
$html .= '<h3>nameString</h3>';
$html .= '<h4>functionString</h4>';
$html .= '</a>';
$html .= '</li>';
// Get Search
$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 users WHERE username LIKE "%'.$search_string.'%" OR name LIKE "%'.$search_string.'%"';
// Do Search
$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['function']);
$display_name = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['name'] . " " . $result['surname'] . " (" . $result['username'] . ")");
$display_url = 'timeline.php?user='.$result['username'];
// 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);
}
}
And the search form itself:
<!-- Main Input -->
<input type="text" id="search" autocomplete="off">
<!-- Show Results -->
<h4 id="results-text">Showing results for: <b id="search-string">Array</b></h4>
<ul id="results"></ul>
All this code can be found here: live search with ajax, php and mysql
credits to him.
thanks for the help in advance!
I got it working thanks to Enijar.
Set the positioning to absolute and the z-index to 99.
Related
I am getting search results from a MySQL table from a string entered in an input text from a HTML page.
Using AJAX, when the user selects one of the result rows the browser is redirected to a PHP file.
What I need is to put the result on another TextField from the same page and not to open another page.
Here is the code that I have now:
PHP part that is sending the needed output results:
/************************************************
Search Functionality
************************************************/
// Define Output HTML Formating
$html = '';
$html .= '<li class="result" >';
$html .= '<img src="iconos_especialidades/logo" width="94" height="94" />';
$html .= '<a target="_blank" href="urlString" >';
$html .= ' '.'<h3>nameString</h3>';
$html .= '</a>';
$html .= '</li>';
// Get Search
$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 tb_especialidades WHERE especialidad LIKE "%'.$search_string.'%" OR especialidad LIKE "%'.$search_string.'%" ORDER BY especialidad';
// Do Search
$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['especialidad']);
$display_name = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['especialidad']);
$display_url = 'opinar_doc_loc.php?id='.$result['id_especialidad'];
if ($result['icono'] == ""){
$display_logo = "nada.jpg";
}
else {
$display_logo = $result['icono'] ;
}
// Insert Name
$output = str_replace('nameString', $display_name, $html);
// Insert URL
$output = str_replace('urlString', $display_url, $output);
// Insert LOGO
$output = str_replace('logo', $display_logo, $output);
// Output
echo($output);
}
}else{
// Format No Results Output
$output = str_replace('urlString', 'javascript:void(0);', $html);
$output = str_replace('nameString', '<b>No se ha encontrado la especialidad buscada.</b>', $output);
$output = str_replace('functionString', 'Sorry :(', $output);
// Insert LOGO
$display_logo = "nada.jpg";
$output = str_replace('logo', $display_logo, $output);
// Output
echo($output);
}
}
And here is the JQuery/Ajax Part:
// Start Ready
$(document).ready(function() {
// Icon Click Focus
$('div.icon').click(function(){
$('input#search').focus();
});
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#search').val();
$('b#search-string').text(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "php/search.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}return false;
}
$("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));
};
});
});
How could I put the needed value from the database $result['id_especialidad'] on a TextField from the HTML page?
You can achieve this by returning a json object with more than one key. For example from php:
<?php
$result = array('id' => $result['id_especialidad'], 'data' => $output);
echo json_encode($result);
?>
Then from JS you can decode and handle as two separate pieces of data:
$.ajax({
type: "POST",
url: "php/search.php",
data: { query: query_value },
cache: false,
success: function(html){
var response = $.parseJSON(html);
$("#my_input_field").val(response.id);
$("ul#results").html(response.data);
}
});
EDIT -------
I've added the correct id field from the query result (see above again), you will also need to edit the output from the no results part of the php file (after the 'else') to echo the json encoded array... for example:
<?php
$result = array('id' => 0, 'data' => $output);
echo json_encode($result);
?>
You question is a little bit confusing...
After click in the result list (LIs), you want to put the redirect page to a text field instead of open a new page ?
If yes, you need to do another ajax to get the page content and them put the content in the text field.
I am working with a wordpress theme called X theme. My lead dev guy bailed and this function is not working. The purpose of it is to flip to the first image in that products gallery when a mousein/out event occurs. The query is looking for a proceeding post ID which is not there or doesn't meet the criteria for the query. So instead I would like it to simply get the image a better way because this doesn't work consistently.
function x_woocommerce_shop_thumbnail() {
GLOBAL $product;
$stack = x_get_stack();
$stack_thumb = 'entry-full-' . $stack;
$stack_shop_thumb = $stack_thumb;
$id = get_the_ID();
$rating = $product->get_rating_html();
woocommerce_show_product_sale_flash();
echo '<div class="entry-featured">';
echo '<a id="id'.$id.'" value="'.$id.'" href="'.get_the_permalink().'">';
echo get_the_post_thumbnail( $id , $stack_shop_thumb );
global $wpdb;
foreach($wpdb->get_results('SELECT ID FROM wp_posts WHERE post_parent = "'.$id.'" AND post_type = "attachment" ORDER BY ID DESC LIMIT 1') as $key => $row){
$file = '_wp_attached_file';
$childId = $row->ID;
global $wpdb;
$query = 'SELECT meta_value FROM wp_postmeta WHERE meta_key = "'.$file.'" AND post_id = "'.$childId.'"';
$otherImage = $wpdb->get_var($query);
if($otherImage != ''){
echo '<img id="otherImage" src="/wp-content/uploads/'.$otherImage.'"/>';
}
}
if ( ! empty( $rating ) ) {
echo '<div class="star-rating-container aggregate">' . $rating . '</div>';
}
echo '</a>';
echo "</div>";
}
The java & jQuery for the flip (is running in the footer of theme)
//Product Hover Image Switch
jQuery(document).ready(function() {
jQuery('[id^=id]').mouseover(function(){
if(jQuery(this).children('#otherImage').attr('src') != ''){
jQuery(this).fadeTo(200, 0, function(){
var source = jQuery(this).children('#otherImage').attr('src'),
original = jQuery(this).children('.wp-post-image').attr('srcset');
jQuery(this).children('.wp-post-image').attr('srcset', source);
jQuery(this).children('#otherImage').attr('src', original);
}).fadeTo(200, 1);
}
});
jQuery('[id^=id]').mouseout(function(){
if(jQuery(this).children('#otherImage').attr('src') != ''){
jQuery(this).fadeTo(200, 0, function(){
var source = jQuery(this).children('#otherImage').attr('src'),
original = jQuery(this).children('.wp-post-image').attr('srcset');
jQuery(this).children('.wp-post-image').attr('srcset', source);
jQuery(this).children('#otherImage').attr('src', original);
}).fadeTo(200, 1);
}
});
});
I have searched the web and mostly using jquery and some library to do so. I wonder how we can do it using pure javascript to make an Infinite Page Scroll Effect like twitter does without having to include any library(here i put the search php and html code for reference, and i wanna realize the effects in the search results. I use laravel as a backend). And i am just starting to learn javascript , please treat me as a 10 year old boy. Thanks
//HTML
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Risky Jobs - Search</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div class="searchWrapper">
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method='get' >
<input type="search" name="search">
</form>
</div>
<h3>Risky Jobs - Search Results</h3>
</body>
</html>
// PHP
function build_query($user_search, $sort){
$search_query = "SELECT * FROM posts";
$clean_search = str_replace(',',' ',$user_search);
$search_words = explode(' ', $clean_search);
//to become a array
$final_search_words = array();
if(count($search_words) > 0){
foreach($search_words as word){
if(!empty($word)){// there are circustances that the user input two or more blank so it will result to a blank result
$final_search_words[] = $word;
}
}
}
// Generate a WHERE clause using all of the search keywords
$where_list = array();
if(count($final_search_words) > 0){
foreach($final_search_words as $word){
$where_list[] = "content Like '%$word%'";
}
}
$where_clause = implode(' OR ', $where_list);
//Add the keyword WHERE clause to the search query
if(!empty($where_clause)){
$search_query .= " WHERE $where_clause";
}
// Sort the search query using the sort setting
switch ($sort) {
// Ascending by title
case 1:
$search_query .= " ORDER BY title";
break;
// Desending by title
case 2:
$search_query .= " ORDER BY title DESC";
break;
// Ascending by created_at
case 3:
$search_query .= " ORDER BY created_at";
break;
// Descending by created_at
case 4:
$search_query .= " ORDER BY created_at DESC";
break;
default:
// No sort setting provided, so don't sort the query
//break;
}
return $search_query;
} //END OF build_query() FUNCTION
// This function builds heading links based on the specified sort setting
function generate_sort_links($user_search, $sort){
$sort_links = '';
switch ($sort) {
case 1:
$sort_links .= '<li>Title</td><td>Description</li>';
$sort_links .= '<li>created_Time</td><td>Description</li>';
break;
case 3:
$sort_links .= '<li>created_Time</td><td>Description</li>';
$sort_links .= '<li>Title</td><td>Description</li>';
break;
default:
$sort_links .= '<li>created_Time</td><td>Description</li>';
}
return $sort_links;
}//end of generate_sort_links
// This function builds navigational page links based on the current page and the number of pages
function generate_page_links($user_search, $sort, $cur_page, $num_pages) {
$page_links = '';
// If this page is not the first page, generate the "previous" link
if($cur_page >1){
$page_links .= '<- ';
}else{
$page_links .= '<- ';
}
// Loop through the pages generating the page number links
//loop through all the pages
for($i = 1; $i <= $num_pages; $i++){
if($cur_page == $i){
$page_links .= ' ' . $i;
//if current page, get rid of the url
}else{
$page_links .= ' ' . $i . '';
//if not current page, add the url to make it point to next page or previous page
}
}
//// If this page is not the last page, generate the "next" link
if($cur_page < $num_pages){
$page_links .= ' ->';
//if not last page, make -> have a url and can point to the previous one
}else{
$page_links .= ' ->';
}
return $page_links;
}//end of generate_page_links function
// Grab the sort setting and search keywords from the URL using GET
$sort = $_GET['sort'];
$user_search = $_GET['usersearch'];
//// Calculate pagination information
$cur_page = isset($_GET['page']) ? $_GET['page'] : 1;
$result_per_page = 5;// number of results per page
$skip = (($cur_page -1) * $results_per_page);
// Start generating the search results
echo '<div class="filter">';
echo generate_sort_links($user_search, $sort);
echo '</div>';
// Connect to the database
require_once('dbinfo.php');
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// Query to get the total results
$query = build_query($user_search, $sort);
$result = mysqli_query($dbc, $query);
$total = mysqli_num_rows($result);
$num_pages = ceil($total / $results_per_page);
// // Query again to get just the subset of results
$query = $query . " LIMIT $skip, $results_per_page";
//limit 10,5 means skip the 10 and return 5
//$skip = (($cur_page -1) * $results_per_page);
$result = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($result)) {
echo '<div class="search_item">';
echo '<div>' . $row['title'] . '</div>';
echo '<div>' . $row['created_at'] . '</div>';
echo '<div>' . substr($row['content'], 0,300) . '</div>';
echo '</div>';//end of search_item wrap
}
// Generate navigational page links if we have more than one page
if($num_pages >1 ){
echo generate_page_links($user_search, $sort, $cur_page, $num_pages);
}
mysqli_close($dbc);
Here you can find an easy way to do an infinite scroll:
JS:
var callback = function test() {
// Log how the height increases to the console
console.log(document.getElementById('infinite').style.height)
// equivalent to $('#infinite') in jQuery
var el = document.getElementById('infinite');
var newHeight = document.getElementById('infinite').offsetHeight + 200;
// Update the height property of the selected element
el.style.height = newHeight + 'px';
}
window.addEventListener('scroll', callback, false);
Basically adding an event listener attached to the scroll, so, every time we scroll, that function is triggered and increase the height property of the element.
You will just need a div as:
<div id='infinite' style='height: 2000px'></div>
Here's a fiddle
Hope it helps :)
What you need to do is an Ajax call on scroll, which appends the products. This question has been asked before and answered over here: On Scroll down how to make ajax call and get the respone data
The code executes an ajax call when a user reaches at end of page. By keeping track of the amount of products, you could send the offset and limit with the ajax call so you could use that within your database query.
EDIT:
Look what I just found: http://www.smarttutorials.net/infinite-scroll-using-jquery-ajax-php-and-mysql/ If this doesn't help...
EDIT 2:
No wordpress so code removed
I have a dynamic search which uses jQuery and a PHP search file to dynamically show the results below. I just changed my log in scripts and sessions; now i am having issues with a search bar that searches through the members in a DB. When I was going through the testing I see that on each keyUp the jQuery function runs properly but there is some sort of issue inside of my search.php file. It seems like there is no $userCount or $userCount = 0 because it will display "There Were No Search Results"which only happens when it equals $userCount== 0
Here are the parts of my index.php
<script type="text/javascript">
function searchUserQ(){
var searchTxt = $("input[name='userSearch']").val();
if (searchTxt == '') {
// $.post("includes/search.php", {searchVal:searchTxt},
// function(output){
// $("#userResults").html(output);
// });
}else{
$.post("includes/search.php", {searchVal:searchTxt},
function(output){
$("#userResults").html(output);
});
console.log(output);
}
}
</script>
<form class="editUser" action="index.php" method="post">
<h1>Search For Employee</h1>
<input type="text" name="userSearch" id="userSearch" placeholder="Search For Employee By First Or Last Name | Press Space To View All Employees" onkeyup="searchUserQ();" />
<submit type="submit" />
div id="userResults">
</div>
</form>
and here is my search.php file
<?php
// this file connects to the database
include("connect.inc.php");
if(isset($_POST['searchVal'])){
// turn that the user searched into a varible
$searchQ = $_POST['searchVal'];
// delete any symbols for security
$searchQ = preg_replace("#[^0-9a-z]#i", "", $searchQ);
$output = "";
// Search through these columns inside the main database
$userSearchQuery = mysql_query("SELECT * FROM dealerEmployees WHERE
firstName LIKE '%$searchQ%' or
lastName LIKE '%$searchQ%'
");
// count the number of results
$userCount = mysql_num_rows($userSearchQuery);
if($userCount == 0){
// $output = "There Were No Search Results";
}else{
while($row = mysql_fetch_array($userSearchQuery)){
// define dynamic varibles for each loop iteration
$id = $row['id'];
$firstName = $row['firstName'];
$lastName = $row['lastName'];
$address = $row['address'];
$phone = $row['phone'];
$email = $row['email'];
$passwordQ = $row['password'];
$permission = $row['permission'];
$photo = "images/" . $row['profilePhoto'];
$output .= "<li><div class='employeeSearch' style=\"background: url('$photo'); width: 75px; height: 75px\"></div><h6>" . $firstName . "</h6>" . " " . "<h6>" . $lastName . "</h6><a href='#' class='employee' data-firstName='$firstName' data-lastName='$lastName' data-address='$address' data-phone='$phone' data-email='$email' data-password='$passwordQ' data-permission='$permission' data-id='$id'>Select Employee</a></li>";
}
}
}
echo $output;
Any suggestions why this is happening?
The reason for the error in the title is that you have console.log(output) outside the callback function. This has two problems: First, the variable output is not in scope; second, it runs immediately, not after the AJAX call returns. Move it into the callback:
function searchUserQ(){
var searchTxt = $("input[name='userSearch']").val();
if (searchTxt != '') {
$.post("includes/search.php", {searchVal:searchTxt},
function(output){
console.log(output);
$("#userResults").html(output);
});
}
}
I have a PHP/Ajax function that returns a list of countries with the given characters in a textbox. Ofcourse Ajax updates this list everytime the textbox gets edited.
Index.PHP calls all the other files, classes and HTML. But when the textbox gets updated, Ajax sends a POST variable to index.PHP because this is where the Search.PHP file with the class name SearchEngine gets called. But because he sends this to the index.php everything keeps getting reloaded and the HTML will be returned twice.
Index.php
<?php
require_once("cgi_bin/connection.php");
require_once("Database_Handler.Class.php");
require_once("HTML_Page.Class.php");
require_once("search.php");
$hostname_conn = "localhost";
$database_conn = "ajax";
$username_conn = "root";
$password_conn = "";
$db = new DatabaseHandler();
$conn = $db->openConnection($hostname_conn, $username_conn, $password_conn, $database_conn);
$IndexPage = new page();
echo $IndexPage->render();
$SearchEngine = new SearchEngine($conn);
?>
Please ignore the poor and unsecure database connection. I am currently transforming all my code to PDO and refining it but that is for later.
Search.PHP
<?php
class SearchEngine{
private $html;
public function __construct($conn){
$this->html = '<li class="result">
<h3>NameReplace</h3>
<a target="_blank" href="ULRReplace"></a>
</li>';
if (isset($_POST["query"])) {
$search_string = $_POST['query'];
}
//$search_string = mysql_real_escape_string($search_string);
if (strlen($search_string) >= 1 && $search_string !== ' ') {
$query = 'SELECT * FROM country WHERE name LIKE "%' . $search_string . '%"';
$result = $conn->prepare($query);
$result->execute();
$result_array = $result->fetchAll();
foreach ($result_array as $result) {
$display_name = preg_replace("/" . $search_string . "/i", "<b>" . $search_string . "</b>", $result['name']);
$display_url = 'sadf';
$output = str_replace('NameReplace', $display_name, $this->html);
$output = str_replace('ULRReplace', $display_url, $output);
echo($output);
}
}
}
}
?>
And as final the Javascript
$(document).ready(function() {
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "index.php", //Referring to index.php because this is where the class SearchEngine is called
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}
return false;
}
$("input#search").keyup(function() {
clearTimeout($.data(this, 'timer'));
var search_string = $(this).val();
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}
else {
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
});
note: HTML is being returned from the "page" class called inside Index.php
How do i not let everything get called twice?
Thank you,
EDIT: A new file was suggested where i direct the ajax url to AutoComplete.php
AutoComplete.PHP
Please explain what should be in the file and why. I am clueless.
Basically, just add a parameter to your Ajax call to tell the index.php its being called by Ajax, and then wrap an if-statement around the two lines that print out your actual index page:
if(!isset($_REQUEST['calledByAjax']))
{
$IndexPage = new page();
echo $IndexPage->render();
}
and in your Ajax call:
data: { query: query_value, calledByAjax: 'true' },
Or make another php page, like ajaxsearch.php that's the same as your index.php but lacking those two lines, and call that in your Ajax call.
First thing (this is a sample, not tested yet)
autocomplete.php
<?php
$search_string = $_POST['query'];
$query = 'SELECT * FROM country WHERE name LIKE "%' . $search_string . '%"';
$result = $conn->prepare($query);
$result->execute();
$result_array = $result->fetchAll();
foreach ($result_array as $result) {
$display_name = preg_replace("/" . $search_string . "/i", "<b>" . $search_string . "</b>", $result['name']);
$display_url = 'sadf';
$output = str_replace('NameReplace', $display_name, $this->html);
$output = str_replace('ULRReplace', $display_url, $output);
}
echo($output);
?>
autocomplete.js
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "autocomplete.php", //Here change the script for a separated file
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}
return false;
}
$("input#search").keyup(function() {
clearTimeout($.data(this, 'timer'));
var search_string = $(this).val();
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
} else {
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
search(); // call the function without setTimeout
}
});
});
Have luck :)