Ajax live search results not shown on my page - javascript

I got a simple ajax live search script that works fine when I type the keyword in my url and visit the php file. But for some reason when I type the keyword in my input field, nothing happens.
What am I doing wrong?
My input field on products.php:
<input type="search" name="keyword" class="producten-icon divider" placeholder="Zoeken..." id="s_search">
And further down the page I got my result div:
<div id="results"></div>
My ajax script:
<script>
$(document).ready(function () {
$("#s_search").on('keyup',function () {
var key = $(this).val();
$.ajax({
url:'includes/fetch_results.php',
type:'GET',
data:'keyword='+key,
beforeSend:function () {
$("#results").slideUp('fast');
},
success:function (data) {
$("#results").html(data);
$("#results").slideDown('fast');
}
});
});
});
</script>
My fetch_results.php:
<?php
include 'connection.php';
$conn = new Connection;
if($_GET['keyword'] && !empty($_GET['keyword']))
{
// Results names
$results = "SELECT `naam` FROM `producten` WHERE `naam` LIKE '%".$_GET['keyword']."%'";
$resultscon = $conn->query($results);
$resultscr = array();
while ($resultscr[] = $resultscon->fetch_assoc());
$eend = #array_map('current', $resultscr);
// echo '<pre>';
// print_r($eend);
// echo '</pre>';
$resultsoverzicht .= '<div style="height:100%;border:10px solid red;">';
foreach($eend as $result){
$resultsoverzicht .= '
<p>'.$result.'</p>';
}
$resultsoverzicht .= '</div>';
echo $resultsoverzicht;
};
?>
When I use the network inspector I don't see anything posted when typing in the input field. Which should be the case with keyup right?

Related

How to solve this "Uncaught ReferenceError: $ is not defined"

I have some code where I need to update a column of a table (MySQL) calling another php file without leaving the page where some tables might allow inline editing.
I have a point in the php echoing of the page, where an icon can be clicked to save input. The code at that point is:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<?php
$sql = "SELECT * FROM table WHERE a_column='certain_value'";
if (mysqli_query($conn, $sql)) {
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$note = $row["note"];
$code = $row["code"];
}
}
}
// some tabled elements not relevant for the issue
echo "<input type='text' id='note_1' name='note_1' value=$note readonly>";
echo "<input type='text' id='new_note' name='new_note'>";
echo "<img src='icon_to_click.png' id='icon_to_click' name='icon_to_click' >";
?>
<script type="text/javascript">
$(document).ready(function() {
$('#icon_to_click').click(function() {
var note_orig = document.getElementById('note_1').value;
var code_val = '<?php echo "$code" ?>';
var note_new = document.getElementById('new_note').value;
if (note_new != note_orig) {
$.ajax({
type: 'POST',
url: 'update_notes.php',
data: {'code': code_val, 'note': note_new},
success: function(response){
document.getElementById('note_1').value = note_new;
}
});
}
});
});
The relevant code of update_notes.php is:
<?php
// connection
$unsafe_note = $_POST["note"];
$code = $_POST["code"];
require "safetize.php"; // the user input is made safe
$note = $safetized_note; // get the output of safetize.php
$sqlupdate = "UPDATE table SET note='$note' WHERE code='$code'";
if (mysqli_query($conn, $sqlupdate)) {
echo "Note updated";
} else {
echo "Problem in updating";
}
// close connection
?>
Now when I run the code and look at the tool, it gives me the error: Uncaught ReferenceError: $ is not defined, linking the error to this line of the previous js code:
$(document).ready(function() {
So, how can I fix that?
It means that you tried to use Jquery in your Javascript Code without calling Jquery Library or the code is called without the library was fully loaded.
I notice :
That you haven't closed your script tag
You use Jquery so you can use $('#id_name') to select element by Id instead of document.getElementById('note_1')
Get element value by using Element.val() instead of Element.value
Try to edit your code like this
<?php
$sql = "SELECT * FROM table WHERE a_column='certain_value'";
if (mysqli_query($conn, $sql)) {
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$note = $row["note"];
$code = $row["code"];
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Some title</title>
</head>
<body>
<form method="post" accept-charset="UTF-8">
<input type='text' id='note_1' name='note_1' value=<?= $code ?> readonly>";
<input type='text' id='new_note' name='new_note'>";
<img src='icon_to_click.png' id='icon_to_click' name='icon_to_click' >";
</form>
<script>
$(document).ready(function() {
$('#icon_to_click').click(function() {
var note_orig = $('#note_1').val();
var code_val = '<?= $code ?>';
var note_new = $('#new_note').val();
if (note_new != note_orig) {
$.ajax({
type: 'POST',
url: 'update_notes.php',
data: {'code': code_val, 'note': note_new},
success: function(response){
$('#note_1').val() = note_new;
}
});
}
});
});
</script>
</body>
</html>
Hey I have faced same error a day before,this is because you have missed using a jquery library script that is needed. please try using some Updated Jquery CDN . :) It will definitely help
OR
include the jquery.js file before any jquery plugin files.

How to implement a live search for multiple text fields inside one column of a table?

I have currently implemented a live search (search as you type) function on text fields. The flow is something like this.
Call a .js file inside the page.
Set the id of the text field to "client-search".
Inside the .js file it is currently listening for on key up events of the "client-search" text field.
If the on key up event is fired, the .js file calls a PHP file that searches the database and returns the output as a list item in an unordered list underneath the "client-search" text field.
This setup currently works but how do implement it in multiple fields inside a single page, since it works using "id" and obviously I can't have multiple IDs in a single page.
HTML:
<div class="input-group">
<input type="text" id="client-search" class="form-control" placeholder="Search for manager...">
<ul class="livesearch" id="client-result" onclick="clickResult()"></ul>
</div>
JS
/* JS File */
// Start Ready
$j(document).ready(function() {
// Icon Click Focus
$j('div.icon').click(function(){
$j('input#client-search').focus();
});
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#client-search').val();
$j('b#search-string').text(query_value);
if(query_value !== ''){
$j.ajax({
type: "POST",
url: "clientsearch.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#client-result").html(html);
}
});
}return false;
}
$j("input#client-search").live("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$j("ul#client-result").fadeOut();
}else{
$j("ul#client-result").fadeIn();
$j(this).data('timer', setTimeout(search, 100));
};
});
});
PHP:
<?php
$serverName = "(local)";
$connectionInfo = array( "Database"=>"CMS");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
} else {
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
$html = '';
$html .= '<li value="myLi" class="myLi">';
$html .= '<small>nameString</small>';
$html .= '<small></small>';
$html .= '</li>';
$search_string = $_POST['query'];
//$search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
if (strlen($search_string) >= 1 && $search_string !== ' ') {
$sql = "SELECT TOP 10 ClientName FROM Client WHERE ClientName LIKE '%" . $search_string . "%'";
$params = array($search_string);
$stmt = sqlsrv_query( $conn, $sql);
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$results_array[] = $row;
}
if (isset($results_array)) {
foreach ($results_array as $result) {
$display_function = $result['ClientName'];
$display_name = $result['ClientName'];
$output = str_replace('nameString', $display_name, $html);
//$output = str_replace('functionString', $display_function, $output);
echo($output);
}
}else{
$output = str_replace('nameString', '<b>No Results Found.</b>', $html);
$output = str_replace('functionString', 'Sorry :(', $output);
echo($output);
}
}
?>

AJAX request to fill a popover working only once to a php file

I have made a simple search bar in which on every .keyup() event,an asynchronous request goes to a php file which then fills the data in the bootstrap popover.
The problem is that in the popover,the data is filled only once,i.e.,when I type the first character,after that the same data is shown even after multiple .keyup() events.
Here is the code:
HTML:
<input type="text" data-placement="bottom" id="search" name="search1" class="search-box" placeholder="Search..." title="Results"/>
AJAX:
$("#search").keyup(function(){
console.log('erer');
//var searchString = $("#search").val();
var data = $("#search").val();
console.log(data);
var e=$(this);
//if(searchString) {
$.ajax({
type: "POST",
url: "do_search.php",
data: {search:data},
success: function(data, status, jqXHR){
console.log('html->'+data+'status->'+status+'jqXHR->'+jqXHR);
e.popover({
html: true,
content: data,
}).popover('show');
},
error: function() {
alert('Error occured');
}
});
//}
});``
PHP:
$word = $_POST['search'];
//echo $word;
//$word=htmlentities($word)
$sql = "SELECT FName FROM user WHERE FName LIKE '%$word%' ";
//echo $sql;
// get results
//$sql = 'SELECT * FROM Profiles';
$end_result = '';
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
#$end_result.='<li>'.$row["FName"].'</li>';
#$_SESSION['fnamer'] = $row['Fname'];
#$end_result.='<li>'.'<a href =view_search.php>'.$row["Fname"].'</a>'.'</li>';
echo '<a href =view_search.php>'.$row["FName"].'</a>';
}
#echo $end_result;
}
Even though in the success parameter of the $.ajax,the data is being printed fine,i.e.,it changes as I enter different alphabets,but the popover content does not change.
Please provide some suggestions to resolve this problem.
The popover is already shown. This is not the correct way of changing the popover content dynamically.
Your code: https://jsfiddle.net/gsffhLbn/
Instead, address the content of the popover directly:
var popover = e.attr('data-content',data);
popover.setContent();
Working solution
Fiddle: https://jsfiddle.net/gsffhLbn/1/

asynchronous commenting using ajax

I'm trying to create a comment system on my website where the user can comment & see it appear on the page without reloading the page, kind of like how you post a comment on facebook and see it appear right away. I'm having trouble with this however as my implementation shows the comment the user inputs, but then erases the previous comments that were already on the page (as any comments section, I'd want the user to comment and simply add on to the previous comments). Also, when the user comments, the page reloads, and displays the comment in the text box, rather than below the text box where the comments are supposed to be displayed. I've attached the code. Index.php runs the ajax script to perform the asynchronous commenting, and uses the form to get the user input which is dealt with in insert.php. It also prints out the comments stored in a database.
index.php
<script>
$(function() {
$('#submitButton').click(function(event) {
event.preventDefault();
$.ajax({
type: "GET",
url: "insert.php",
data : { field1_name : $('#userInput').val() },
beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
$("#comment_part").html(html);
window.location.reload();
}
});
});
});
</script>
<form id="comment_form" action="insert.php" method="GET">
Comments:
<input type="text" class="text_cmt" name="field1_name" id="userInput"/>
<input type="submit" name="submit" value="submit" id = "submitButton"/>
<input type='hidden' name='parent_id' id='parent_id' value='0'/>
</form>
<div id='comment_part'>
<?php
$link = mysqli_connect('localhost', 'x', '', 'comment_schema');
$query="SELECT COMMENTS FROM csAirComment";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="comment" >';
$output= $row["COMMENTS"];
//protects against cross site scripting
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8');
echo '</div>';
}
?>
</div>
insert.php
$userInput= $_GET["field1_name"];
if(!empty($userInput)) {
$field1_name = mysqli_real_escape_string($link, $userInput);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO csAirComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
//header("Location:csair.php");
die();
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
}
The insert.php takes in the user input and then inserts it into the database (by first filtering and checking for bad words). Just not sure where I'm going wrong, been stuck on it for a while. Any help would be appreciated.
There are 3 main problems in your code:
You are not returning anything from insert.php via ajax.
You don't need to replace the whole comment_part, just add the new comment to it.
Why are you reloading the page? I thought that the whole purpose of using Ajax was to have a dynamic content.
In your ajax:
$.ajax({
type: "GET",
url: "insert.php",
data : { field1_name : $('#userInput').val() },
beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
//this will add the new comment to the `comment_part` div
$("#comment_part").append(html);
}
});
Within insert.php you need to return the new comment html:
$userInput= $_GET["field1_name"];
if(!empty($userInput)) {
$field1_name = mysqli_real_escape_string($link, $userInput);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO csAirComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
mysqli_close($link);
//here you need to build your new comment html and return it
return "<div class='comment'>...the new comment html...</div>";
}
else{
die('comment is not set or not containing valid value');
}
Please note that you currently don't have any error handling, so when you return die('comment is not set....') it will be displayed as well as a new comment.
You can return a better structured response using json_encode() but that is outside the scope of this question.
You're using jQuery.html() which is replacing everything in your element with your "html" contents. Try using jQuery.append() instead.

Ajax, PHP Live search & show more code works separately but not together

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);
}
}

Categories