I am looking for some initial direction on this one because I cannot seem to find my way with it. Let me explain... I'm creating a music website and having a search bar. It filters information as the user types. I don't want to make a separate .php file for each song on the website. (Eg: song1.php, song2.php, etc...). There should be one PHP template file, that outputs the webpage for ALL songs. With my code, when I try searching with the search bar, it opens the template file as expected but it fills the file with information of only the first row from the mysql table. This is the form, its in the index page:
<script type = "text/javascript "src = "jquery.js">
<form class="navbar-form navbar-left" >
<div class="form-group">
<input type="text" class="form-control" id="search" placeholder="Search for songs, artists" autocomplete="off">
<div id = "searchresults"> </div>
Then there's the search.js file having two tasks, that is to check if a result has been clicked and also if the user has pressed a key. Its like this:
$('#search').keyup(function()
{
var searchterm = $ ('#search').val();
if (searchterm != '')
{
$.post('search.php', {searchterm:searchterm},
function(data)
{
$('#searchresults').html(data);
});
}
else{
$('#searchresults').html('');
}
});
$('#mylink').click(function(){
var wanted = $('#mylink').val();
$.post('/web/ztemplate.php', {wanted:wanted});
});
I think it's the one having an error but I can't figure out where it is. The template file has this php code :
$search = $_POST['wanted'];
$find = mysql_query("SELECT * FROM search WHERE title LIKE '%$search%'");
$row = mysql_fetch_assoc($find); $title = $row["title"];
There's a search.php file which queries the database to provide information for the instant search. It looks like this :
$search = mysql_real_escape_string(trim($_POST['searchterm']));
if ($search == '' && ' '){
echo 'No results found';
}
else {
$find_videos = mysql_query("SELECT * FROM search WHERE keywords LIKE '%$search%'");
$count = mysql_num_rows($find_videos);
if ($count ==0){
echo 'No Results found for '.$search;
}
else {
while($row = mysql_fetch_assoc($find_videos)){
$title = $row["title"];
$link = $row["link"];
echo "<a href = '$link'><h5 id = 'mylink'> $title <h5> </a> <hr /> ";
}
}
}
Any help is much appreciated.
why you not send an AJAX??
$('#search').keyup(function(){
var searchterm = $ ('#search').val();
if (searchterm != ''){
$.ajax({
type: 'POST',
data: {
"searchterm": searchterm,
"_token":"{{ csrf_token() }}"
},
url: "{{URL::asset('yourPHP')}}",
success: function(response){
$('#searchresults').html(response);
}
});
}else{
$('#searchresults').html('');
}
});
PHP
function searchSong($search =''){
$search = (trim($_POST['searchterm']));
$out='';
if ($search == '' && ' '){
echo 'No results found';
}else {
$sql = "SELECT * FROM search WHERE title LIKE '%$search%'";
$data= DB::select($sql);
$count = count($data);
if ($count ==0){
echo 'No Results found for '.$search;
}else {
foreach ($data as $key => $row) {
$title = $row["title"];
$link = $row["link"];
$out .= "<a href = '$link'><h5 id = 'mylink'> $title </h5> </a> <hr /> ";
}
}
}
return $out;
}
Related
Below is the index page: having these code: Data gets populated in a div as expected.
<h2>Search for users</h2>
<input type="text" name="search" id="search" autocomplete="off" placeholder="Enter Customer ID here....">
<div id="output"></div>
<script type="text/javascript">
$(document).ready(function(){
$("#search").keyup(function(){
var query = $(this).val();
if (query != "") {
$.ajax({
url: 'ajax-db-search.php',
method: 'POST',
data: {query:query},
success: function(data){
$('#output').html(data);
$('#output').css('display', 'block');
$("#search").focusin(function(){
$('#output').css('display', 'block');
});
}
});
} else {
$('#output').css('display', 'none');
}
});
});
</script>
This is the ajax-db-search.php page. (In the IF tags I tried it with == and no good luck yet.)
<?php
$conn=mysqli_connect("*****","*********","******","*****");
$query = "SELECT * FROM `create_customer` WHERE `Customer Id` LIKE '{$_POST['query']}%' LIMIT 6";
$result = mysqli_query($conn, $query);
$plan = $query['Plan'];
if ($plan = "planA") {
while ($user = mysqli_fetch_array($result)) {
echo "<h2>".$user['Customer Name']."</h2>";
echo "<h4><a href='http://smjw.phatake.in/admin/cc.php?recordID=".$user['id']."'>Update Profile Details</a></h4>";
echo "<h4><a href='http://smjw.phatake.in/admin/planA_details.php?recordID=".$user['Customer Id']."'>Receive Payment</a></h4>";
var_dump ($plan);
}
}
if ($plan = "planB") {
while ($user = mysqli_fetch_array($result)) {
echo "<h2>".$user['Customer Name']."</h2>";
echo "<h4><a href='http://smjw.phatake.in/admin/cc.php?recordID=".$user['id']."'>Update Profile Details</a></h4>";
echo "<h4><a href='http://smjw.phatake.in/admin/planB_details.php?recordID=".$user['Customer Id']."'>Receive Payment</a></h4>";
}
}
if ($plan = "planC") {
while ($user = mysqli_fetch_array($result)) {
echo "<h2>".$user['Customer Name']."</h2>";
echo "<h4><a href='http://smjw.phatake.in/admin/cc.php?recordID=".$user['id']."'>Update Profile Details</a></h4>";
echo "<h4><a href='http://smjw.phatake.in/admin/planC_details.php?recordID=".$user['Customer Id']."'>Receive Payment</a></h4>";
}
}
if ($plan = "planA1") {
while ($user = mysqli_fetch_array($result)) {
echo "<h2>".$user['Customer Name']."</h2>";
echo "<h4><a href='http://smjw.phatake.in/admin/cc.php?recordID=".$user['id']."'>Update Profile Details</a></h4>";
echo "<h4><a href='http://smjw.phatake.in/admin/planA1_details.php?recordID=".$user['Customer Id']."'>Receive Payment</a></h4>";
}
}
else {
echo "<p style='color:red'>User not found...</p>";
}
?>
The Problem is with the If condition: The Url's that needs to be displayed on my index page should change according to the $plan variable. But for some reason the $plan variable is always planA..
There are 4/5 Plans.. planA, planB, planc, planA1 each having different Urls that needs to displayed.
The URL do get populated but will be always the First IF conditions URL for all the customers.
Please help me out with this. Stuck for big time.
-------Update-------------
I want each of the Receive Payment to be according to the if conditions.. Now its all only planA
Here i am using php pdo for perform the search task.
i am create a two file 'search.php' is a send ajax request to query.php file.
search.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Search</title>
<!-- jQuery cdn link -->
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
</head>
<body>
<input type="text" id="search" placeholder="Search">
<div class="table-div" style="display: none"></div>
</body>
</html>
<script>
$(document).ready(function(){
$("#search").keyup(function(){
$.get("/query.php", {data:$(this).val()}, function(data, status){
let row = JSON.parse(data);
let table = "";
table += "<table>";
table += "<thead>";
table += "<tr>";
table += "<th>Customer name</th><th>Customer salary</th>";
table += "</tr>";
table += "</thead>";
table += "<tbody>";
if(row.data != "No data found") {
$.each(row.data, function(key, value){
table += "<tr>";
table += "<td>"+ value.customer_name +"</td>";
table += "<td>"+ value.cust_sal +"</td>";
table += "</tr>";
});
}
table += "</tbody>";
table += "</table>";
$(".table-div").html(table);
$(".table-div").show();
});
});
});
</script>
query.php
<?php
// This is a database connectivity
$conn = new PDO("mysql:host=localhost; dbname=test;", 'root', '');
if(isset($_GET['data']))
{
$query = "%".$_GET['data']."%";
$searchSQL = "SELECT * FROM cust WHERE customer_name LIKE :cname";
$searchState = $conn->prepare($searchSQL);
$searchState->bindParam(":cname", $query);
if($searchState->execute())
{
if($searchState->rowCount() > 0)
{
$data = $searchState->fetchAll();
}
else
{
$data = "No data found";
}
}
echo json_encode(["data" => $data]);
}
?>
Hmm you said you tried == it should be == and not =.
Firstly please note your sql queries any kind of query should be prepare statements even if you trust your users.
Now please note that:
echo "planA"=="plana" ? "yes" : "no"; // Output no. Have you tried this?
Edit: I overlooked " But for some reason the $plan variable is always planA.." that is because of = in your ifs
$plan = "";
if ($plan = "a") {
echo $plan;
}
if ($plan = "b") {
echo $plan;
}
if ($plan = "c") {
echo $plan;
}
//output: abc
Lastly, please use else if, you don't need to check if 3 times it can only be 1 option.
Edit 2: I think you have some way to go. Please have look at the code below.
Here is the complete working with your bug I think:
<?php
// Since I have no post i will set it by default
$_POST['query'] = 'AZ12';
// Check for data validation...
if (!isset($_POST['query']) || empty($_POST['query'])) return;
// Now for query
$query = "SELECT * FROM `create_customer` WHERE `Customer Id` LIKE ? LIMIT 6";
// Prepare the statement to insert user_answer in ? above
// replace "s" based on your appropriate var type
$stmt = $conn->prepare($query);
// $stmt->bind_param("s", "%".$_POST['query']."%"); <-- This would yield error
// ^ fix: Store the 2nd param first
$like = "%{$_POST['query']}%";
$stmt->bind_param("s", $like);
$stmt->execute();
// Get the results
$result = $stmt->get_result();
echo "<br/>";
print_r($result);
// Output: mysqli_result Object ( [current_field] => 0 [field_count] => 3 [lengths] => [num_rows] => 1 [type] => 0 )
// ^ This will show all the elements part of $result (your case 6)
// Why this? Because to me it seems like you have hard-coded plans
// because if $plan = A,B,C and then you insert while loop inside the if's
$plans = array(0 => 'PlanA', 1 => 'PlanB', 2 => 'PlanC');
foreach($plans as $value) {
echo "<h1>$value</h1><br/>";
// Now loop as assoc like you have...
while ($row = $result->fetch_assoc()) {
print_r($row);
// ^ With above get the data value you need such as:
// echo "<h2>".$row['Customer Id']."</h2>";
}
// Add this to fix the fetch_assoc
$result->data_seek(0); // without this you will see the image below
}
// ^ Output Notice we only show plan A rows!!! look image below.
// Fix indicate by $result->data_seek(0);
?>
I am assuming this is what you get: "Why only A show?"
code:
<script>
$(document).ready(function(){
$(".choose").click(function(){
job_type = $(':checked').map(function() {
return this.value;
}).get().join(',');
category = $("#cat_gory").val();
$.ajax({
type:"POST",
data:{"job_type":job_type,"category":category},
url:"type-jobs.php",
success:function(data){
$(".success").html(data);
}
});
});
});
</script>
<input type="hidden" name="cat_gory" id="cat_gory" value="<?php echo $job_category; ?>" />
<p class="flchek">
<input type="checkbox" name="choosetype" value="freelance" class="choose" id="33r">
<label for="33r">Freelance</label>
</p>
<p class="ftchek">
<input type="checkbox" name="choosetype" value="full time" class="choose" id="dsf">
<label for="dsf">Full Time</label>
</p>
<p class="ischek">
<input type="checkbox" name="choosetype" value="internship" class="choose" id="sdd">
<label for="sdd">Internship</label>
</p>
<div class="success"></div>
type-jobs.php
<?php
include("config.php");
$job_category = mysqli_real_escape_string($con,$_POST['category']);
$job_type = mysqli_real_escape_string($con,$_POST['job_type']);
$tag = explode(",",$job_type);
foreach($tag as $type)
{
$sql_job = mysqli_query($con,"select p.job_title,c.state,c.city from company c inner join jobs p on p.company_name = c.company_name where p.category = '".$job_category."' and job_type='".$type."'");
$result_job = mysqli_num_rows($sql_job);
if($result_job > 0)
{
while($row_jobs = mysqli_fetch_array($sql_job))
{
echo '<h3>'.$row_jobs['job_title'].'</h3>';
}
}
else
{
echo '<p id="c_mm">record not found</p>';
}
}
?>
In this code I have multiple checkbox. Now, When I click on checkbox to get data through jquery/ajax it return data to me but the problem is if I click on freelance checkbox it show me record not found again when I click on full time then it showing record not found as well as jobs. Now, I want if data was not found in my database it will show single message to me and if data found then hide message and show database record. So, How can I do this? Please help me.
Thank You
NO need to explode the $jobtype Use 'jobtype IN('.$jobtype.') '
<?php
include("config.php");
$job_category = mysqli_real_escape_string($con,$_POST['category']);
$job_type = mysqli_real_escape_string($con,$_POST['job_type']);
$sql_job = mysqli_query($con,"select p.job_title,c.state,c.city from company c inner join jobs p on p.company_name = c.company_name where p.category = '".$job_category."' and job_type IN('".$jobtype."') ');
$count = mysqli_num_rows($sql_job);
$row_data = mysqli_fetch_array($chek_result);
if($count > 0){
foreach($row_data as $data){
$message = '<h3>'.$data['job_title'].'</h3>';
}
}else{
$message = "No Data found";
}
echo $message;exit;
?>
If you want to show record not found message only if you don't find any record then you can use a flag in php something like this:
<?php
include("config.php");
$job_category = mysqli_real_escape_string($con,$_POST['category']);
$job_type = mysqli_real_escape_string($con,$_POST['job_type']);
$found = 0;
$message = '';
$tag = explode(",",$job_type);
foreach($tag as $type)
{
$sql_job = mysqli_query($con,"select p.job_title,c.state,c.city from company c inner join jobs p on p.company_name = c.company_name where p.category = '".$job_category."' and job_type='".$type."'");
$result_job = mysqli_num_rows($sql_job);
if($result_job > 0)
{
$found = 1;
while($row_jobs = mysqli_fetch_array($sql_job))
{
$message .= '<h3>'.$row_jobs['job_title'].'</h3>';
}
}
}
if(found == 0) {
$message = '<p id="c_mm">record not found</p>';
}
echo message;
?>
Notice $found flag here in code. HTH.
I've got some problem!
I want to show both news-evt and news-ntc content in my web page.
The JS can POST "news-evt, news-ntc", but the PHP cannot process with this result, how can I do? I am new of php and ajax... Thanks!
My Table:
**id** **category**
0 news-evt
1 news-ntc
My HTML:
<ul id="blog-filters">
<li data-vid="news-evt, news-ntc"><a>All</a></li>
<li data-vid="news-evt"><a>Event</a></li>
<li data-vid="news-ntc"><a>Notice</a></li>
</ul>
My JS:
$(document).ready(function() {
$(document).on('click', '#blog-filters li', function(){
var last_id = $(this).data("vid");
$.ajax(
{
url:"load_data.php",
method:"POST",
data:{last_id:last_id},
dataType:"text",
success:function(data) {
if(data !== '') {
$('.post-item').remove();
$('.btn-load-more').remove();
$('.blog-content-rows').append(data);
} else {
$('.btn-load-more a').html("No More...");
}},
});
});
});
My PHP:
if (isset($_POST['last_id'])){
require_once('datalogin.php');
$last_id = ($_POST['last_id']);
$showLimit = 3;
$output = '';
$id = '';
sleep(1);
$raw_results = mysql_query("SELECT * FROM article WHERE (category LIKE '%".$last_id."%') ORDER BY date DESC LIMIT ".$showLimit) or die(mysql_error());
if(mysql_num_rows($raw_results) > 0) {
while($results = mysql_fetch_array($raw_results)) {
$id = $results['id'];
$output .= 'Something Code...';
}
}
}
Solved: Simply change$last_id = $_POST['last_id'] to $last_id = explode(',',$_POST['last_id']) and then add foreach ($last_id as $item) {$raw_results = mysql_query............}
New Problem: But there is a Order problem...the foreach loop output 'evt' result first...
You can always use the echo of PHP.
<div class="blog-content-rows">
<?php
if (isset($_POST['last_id'])){
require_once('datalogin.php');
$last_id = ($_POST['last_id']);
$showLimit = 3;
$output = '';
$id = '';
sleep(1);
$raw_results = mysql_query("SELECT * FROM article WHERE (category LIKE '%".$last_id."%') ORDER BY date DESC LIMIT ".$showLimit) or die(mysql_error());
if(mysql_num_rows($raw_results) > 0) {
while($results = mysql_fetch_array($raw_results)) {
$id = $results['id'];
$output .= 'Something Code...';
//new code here:
echo "<div>ID: ". $id ."<br/> Output: ". $output ."</div>";
}
}
}
?>
</div>
The result would be like:
<div class="blog-content-rows">
<div>ID: 1<br/> Output: Some_text</div>
<div>ID: 2<br/> Output: Some_other_text</div>
<div>ID: 3<br/> Output: Another_text</div>
</div>
Feel free to ask for anything else.
I have jQuery ListView that loads data from a php file. I also have a checkbox that onclick should be able to filter the list. The filtering is done by sending a post message to server and refreshing the list. However, the checkbox list is not filtering the list. The code below is only part of the whole implementation. Here is the page:
http://i.cs.hku.hk/~hsbashir/Project_Work/Listview/restaurant_list.html
This is the HTML implementation:
<head>
<script>
lastRecord=0;
function loadRest(){
$('#sample').html( 'hello' );
$.get(
"queryRestaurantsList.php?lastRecord="+lastRecord,
function( data ) {
$('#rest_mesgs').append( data )
.listview( 'refresh' );
}
);
}
</script>
</head>
<body onload="loadRest()">
<div data-demo-html="true">
<form>
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>Select your type of Restaurant:</legend>
<input type="checkbox" name="checkbox-h-2a" id="checkbox-h-2a" onchange="onfilter()" value="Vegetarian"/>
<label for="checkbox-h-2a">Vegetarian</label>
</fieldset>
</form>
</div>
<div data-demo-html="true">
<ul data-role="listview" data-theme="a" data-split-theme="b" data-split-icon="plus" data-inset="true" id="rest_mesgs">
<li data-role="list-divider">Restaurants</li>
</ul>
</div>
<script>
function onfilter(){
if($("#checkbox-h-2a").prop('checked')){
document.getElementById("hehe").innerHTML = "if condition is true";
var a = document.getElementById("checkbox-h-2a");
$.post("queryRestaurantsList.php",
{
filter0 : a.value;
},
function(data){
$('#rest_mesgs').append( data )
.listview( 'refresh' );
});
}
else {
document.getElementById("hehe").innerHTML = "not working";
}
}
</script>
</body>
This is php file:
mysql_connect($host,$username,$password);
mysql_select_db($database) or die( "Unable to select database");
//Check if POST array is empty or not
if ($_POST == null){
$query = "SELECT Name,Short_Loc,Image_Link,Type FROM Restaurant_Info";
$result = mysql_query($query) or die( "Unable to execute query");
while ($row = mysql_fetch_array($result)){
print '<li>';
print '<a href="'.$row['Full_Link'].'">';
print '<img style="height:80px;" src="'.$row['Image_Link'].'">';
print '<h2 style="text-wrap : normal">'.$row['Name'].'</h2>';
print '<p id="type" class="ui-li-aside"><strong>'.$row['Type'].'</strong></p>';
print '<p>'.$row['Short_Loc'].'</p>';
print '</a>';
print '</li>';
}
}
else {
$value1 = $_POST[filter0];
$query0 = 'SELECT Name,Short_Loc,Image_Link FROM Restaurant_Info WHERE Type LIKE ';
$query0 = $query0.'"%'.$value1.'%"';
$result = mysql_query($query0) or die( "Unable to execute query");
$num_results = mysql_num_rows($result);
if ($num_results == 0){
print "Your criteria does not match any of the restaurants";
}
else{
while($row = mysql_fetch_array($result)) {
print '<li>';
print '<a href="'.$row['Full_Link'].'">';
print '<img style="height:80px;" src="'.$row['Image_Link'].'">';
print '<h2 style="text-wrap : normal">'.$row['Name'].'</h2>';
print '<p>'.$row['Short_Loc'].'</p>';
print '</a>';
print '</li>';
}
}
I can see 2 errors, but unfortunately I can't test them.
1 - This php part:
else {
$value1 = $_POST[filter0];
Should be replace with:
else {
$value1 = $_POST['filter0'];
Otherwise filter0 will be treated as a constant instead of a string.
2 - On your html, you did:
<input type="checkbox" name="checkbox-h-2a" id="checkbox-h-2a" onchange="onfilter()" value="Vegetarian"/>
This should be
<input type="checkbox" name="checkbox-h-2a" id="checkbox-h-2a" onclick="onfilter()" value="Vegetarian"/>
I think a checkbox won't fire onchange when you check or uncheck it.
1 . To maintain checkbox state change use jQuery.toggle(). It's the safest way.
$("#checkbox-h-2a").toggle(function(){
var filter = $(this).val();
getListviewItems({filter0: filter});
}, function() {
getListviewItems();
});
2 . Make one function with params for getting list items. That way you'll keep your code clean and easy to maintain.
function getListviewItems(opt) {
opt.filter0 = (opt.filter0 == undefined)?'':opt.filter0;
/* Body of function, post and/or get calls, etc. */
}
I have a comics website. A feature it has is to allow users to search comics... the search will instantly parse the input and return thumbnail results based on matching title and keywords.
Originally, the search would return all of the results, and the bounding search box would expand infinitely downward, holding every single comic result. I thought it may be a nice touch to limit the results to 4, and display a message like "load 5 remaining images" if the user chooses to do so.
If they click on that message, I wanted limiting php variable to be removed or changed.
So far, it loads with the limit, and shows a link...
EDIT: Latest Code:
search_field.php (the search file that get's included on a page... this file calls search.php via JQuery):
<?php $site = (isset($_GET['site']) ? ($_GET['site']) : null); ?>
<div id="sidebar" class="searchborder">
<!--Allow users to search for comic-->
<!--<span class="search">Search for <?php// echo (($site == "artwork") ? 'artwork' : 'a comic'); ?> </span>-->
<script type="text/javascript">
function GetSearch(mySearchString){
$.get("./scripts/search.php", {_input : mySearchString, _site : '<?php echo $site ?>'},
function(returned_data) {
$("#output").html(returned_data);
}
);
}
</script>
<center>
<table>
<tr>
<td>
<span class="search">
<img src="./images/SiteDesign/Search.png" />
<input type="text" onkeyup="GetSearch(this.value)" name="input" value="" />
<!--<input id="site" type="hidden" value="<?php// echo $site; ?>">-->
</span>
</td>
</tr>
</table>
</center>
<span id="output"> </span>
</div>
search.php, the file that's called to parse the string and return the results:
<?php
//Query all images:
include 'dbconnect.php';
$site = $_GET['_site'];
$input = (isset($_GET['_input']) ? ($_GET['_input']) : 0);
$siteChoice = (isset($_GET['_choice']) ? ($_GET['_choice']) : $site);
$start = (isset($_GET['_start']) ? ($_GET['_start']) : null);
echo "start: " . $start;
//if user goes to hittingtreeswithsticks.com... no "site" value will be set... so I need to set one
if ($site == null) {
$site = "comics";
}
if ($siteChoice == "artwork") {
$sql = "SELECT id, title, keywords, thumb FROM artwork";
$thumbpath = "./images/Artwork/ArtThumbnails/";
}
else if ($siteChoice == "comics") {
$sql = "SELECT id, title, keywords, thumb FROM comics";
$thumbpath = "./images/Comics/ComicThumbnails/";
}
else {
$sql = "SELECT id, title, keywords, thumb FROM $site";
if ($site == "artwork") {
$thumbpath = "./images/Artwork/ArtThumbnails/";
}
else {
$thumbpath = "./images/Comics/ComicThumbnails/";
}
}
/* For this to work, need all comics replicated in an "All Comics" file along with "All Thumbnails"
else {
$sql = "SELECT id, title, thumb FROM comics
UNION
SELECT id, title, thumb FROM artwork";
$thumbpath = "./images/AllThumbnails/";
}*/
$imgpaths = $mysqli->query($sql);
mysqli_close($mysqli);
$idresult = array();
$imgresult = array();
$thumbresult = array();
//CHECK IF $INPUT == IMAGE PATH
if (strlen($input) > 0)
{
while ($row = $imgpaths->fetch_assoc())
{
//query against key words, not the image title (no one will remember the title)
if (stripos($row['keywords'], $input) !== false || strtolower($input)==strtolower(substr($row['title'],0,strlen($input))))
//if (strtolower($input)==strtolower(substr($row['title'],0,strlen($input))))
{
array_push($idresult, $row['id']);
array_push($imgresult, $row['title']);
array_push($thumbresult, $row['thumb']);
}
}
//ECHO RESULTS ARRAY
if(count($imgresult) == 0)
{
echo "<p>no suggestions</p>";
}
else
{
echo "<ul>";
$k = 0;
$max = 4;
if (count($imgresult) > $max) {
while ($k < count($imgresult) && $k < $max)
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
$difference = count($imgresult)-$k;
echo "<br/><i><a href='.?action=homepage&site=" . $siteChoice . "&start=4' class='loadSearch'>load " . $difference . " more result" . (($difference != 1) ? 's' : '') . "... </a></i>";
}
else {
while ($k < count($imgresult))
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
}
echo "</ul>";
}
}
?>
<script type="text/javascript">
$(".loadSearch").click(function() {
//alert("Test");
$.get("./search.php", {_start : 4},
function (returned_data) {
$("#moreResults").html(returned_data);
}
);
});
</script>
Try this:
<script type="text/javascript">
$("#loadSearch").click(function() {
$.get('URL WITH QUERY', function(data) {
$('#results').html(data);
});
});
</script>
From what i get all you need is when "load more" is clicked only new results should be shown.
Load more has to be a url same as your search url.
Search/Autocomplete URL - example.com/autocomplete?q=xkd
Load More URL - example.com/autocomplete?q=xkd&start=4&max=1000
Just add two parameters to your url. start and max. Pass them to your queries and you get exact result.
Only verify Start < Max and are integers intval() and not 0 empty(). Also if Max <= 4 then dont show load more.
I would give all of your results back, then try to determine your results. If more then 4, loop out the first 4 results. If the user clicks on the load more button your start looping from your 4th element. That way you only need to hit the server once (per search).
Try to give back your results in json, so you can format it the way you like in your html file.
In pseudo code:
searchTerm = 'hello';
resultsFromServer = getResults($searchterm);
resultcounter = count(resultsFromServer);
if(resultcounter > 4)
loop 4 results
else
loop all results
$(".loadSearch").click(function(e) {
//alert("Test");
e.preventDefault();
$.get("./search.php", {_start : 4},
function (returned_data) {
$("#moreResults").html(returned_data);
}
);
I ended up going with jquery show and hide functions.
PHP Snippet:
//ECHO RESULTS ARRAY
if(count($imgresult) == 0)
{
echo "<p>no suggestions</p>";
}
else
{
echo "<ul>";
$k = 0;
$max = 4;
while ($k < count($imgresult) && $k < $max)
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
$difference = count($imgresult)-$k;
echo '<div id="moreResults">';
while ($k < count($imgresult))
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
echo '</div>';
if (count($imgresult) > $max) {
?>
<br />Load <?php echo $difference; ?> more result<?php echo (($difference != 1) ? 's' : ''); ?>...
<?php
}
echo "</ul>";
}
}
Jquery:
<script type="text/javascript">
$("#moreResults").hide();
$("#showMore").click(function() {
$("#moreResults").show();
$("#showMore").hide();
});