Search box for website - javascript

I have tried this code and this is working only for one page when i am in basintap page but i want to know how to search anything when i am in another page?
<?php
$query = $_GET['query'];
$min_length = 2;
if(strlen($query) >= $min_length){
$sql ="Select * from basintap where keywords like '%keywords%'";
$run_query = mysqli_query($con,$sql);
if(mysqli_num_rows($run_query) > 0){
while($row = mysqli_fetch_array($run_query)){
$id = $row['id'];
$cat = $row['cat'];
$brand = $row['brand'];
$name = $row['name'];
$image = $row['image'];
echo "<div class='col-md-4'>
<div class='panel panel-info'>
<div class='panel-heading'>$name</div>
<div class='panel-body'>
<img src='basintap/$image' style='width:160px; height:250px;'/>
</div>
</div>
</div> ";
}
}
?>

If you have a separate table per page, then you are going to have to restructure your database in order to solve your problem using a home grown solution. Keep all pages in one table, distinguished by a separate field and/or index.
Alternatively if it's too much hassle, just plug Algolia into your site.

You should probably change your "basintap" string from your query with the table name you'd like to search into.
$sql ="Select * from [place-table-name-here] where keywords like '%keywords%'";

Related

Button from a ajax post page doesnt work when clicked [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 1 year ago.
I have a commenting project that has a button id #see_more_comments inside my .user__comments__container div that is being outputted from a getcomments-afunc.php file via jquery post when the comment is more than 4. The file code of ajax.php is:
<?php
session_start();
include_once '../dbh-inc.php';
if (isset($_SESSION['userid'])) {
$jobsid = mysqli_real_escape_string($conn, $_POST['jid']);
$output = "";
$sql = "SELECT * FROM comments AS c INNER JOIN users AS u ON c.usersId = u.usersId WHERE c.jobsId = '$jobsid' ORDER BY c.cid DESC LIMIT 4;" ;
$result = mysqli_query($conn, $sql);
$commentcount = 3;
if (mysqli_num_rows($result) > $commentcount) {
while ($row = mysqli_fetch_assoc($result)) {
$usersid = $row['usersId'];
$commenterprofilepic = $row['usersProfilePic'];
$username = $row['usersName'];
$usersusername = $row['usersUsername'];
$commentDesc = $row['commentDesc'];
$commentDate = $row['commentDate'];
$output .= '<div class="user__comments">
<img src="profilepic/'.$commenterprofilepic.'" alt="'.$username.'\'s profile picture" class="profile__thumbnail" onclick="location.href=\'profile?uid='.$usersid.'\'">
<div class="comment__bubble">
<div class="comment__box">
<p class="username" onclick="location.href=\''.$usersusername.'\'">'.$username.'</p>
<p class="comment">'.nl2br($commentDesc).'</p>
</div>
<p class="date">'.$commentDate.'</p>
</div>
</div>';
}
$output .= '<div class="see__more__comments" id="see_more_comments">See more comments..</div>';
}
echo $output;
}
else {
header("../../dashboard.php");
exit();
}
Now, when it is outputted to my index.php via a jquery post call, it is registered and can be seen at the elements tab of my browser or DOM.
It is outputted via this jquery code:
setInterval(() => {
$.post('includes/ajax-func/getcomments-afunc.php', {
jid : pageId
}, function (response) {
$('.user__comments__container').html(response);
});
}, 10000
);
However, when I am clicking so that it will add 4 more comments to my .user__comments__container index.php. It doesnt work, I tried making a console.log for it but it hasnt outputted anything, this is the code for clicking the button:
$('#see_more_comments').click(function() {
commentCount = commentCount + 4;
$('.user__comments__container').load('includes/ajax-load/seemorecomments-aload.php' , {
jobsId : pageId,
newCommentCount : commentCount
});
console.log(commentCount);
});
And this is the seemorecomments-aload.php content:
<?php
session_start();
include_once '../dbh-inc.php';
$jobsid = $_POST['jobsId'];
$newcommentcount = $_POST['newCommentCount'];
$sql = "SELECT * FROM comments AS c INNER JOIN users AS u ON c.usersId = u.usersId WHERE c.jobsId = '" . $jobsid . "' ORDER BY c.cid DESC LIMIT $newcommentcount;" ;
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
$usersid = $row['usersId'];
$commenterprofilepic = $row['usersProfilePic'];
$username = $row['usersName'];
$usersusername = $row['usersUsername'];
$commentDesc = $row['commentDesc'];
$commentDate = $row['commentDate'];
echo '<div class="user__comments">
<img src="profilepic/'.$commenterprofilepic.'" alt="'.$username.'\'s profile picture" class="profile__thumbnail" onclick="location.href=\''.$usersusername.'\'">
<div class="comment__bubble">
<div class="comment__box">
<div class="username" onclick="location.href=\''.$usersusername.'\'">'.$username.'</div>
<div class="comment">'.$commentDesc.'</div>
</div>
<div class="date">'.$commentDate.'</div>
</div>
</div>';
}
Before all of this, I have all getcomments-afunc.php content without the $output, $output is replaced by echo, inside my index.php .user__comments__container and it worked just fine..
However, when I decided to add jquery to it so that I wont need to reload the wholepage, my purpose of letting the .user__coments__container reload itself worked but the button doesnt work anymore.
Any help? thank you!! :(
Change the line
$('#see_more_comments').click(function() {
To
$(document).on("click","#see_more_comments",function() {
Thanks Mr. Majid Ali and Mr. Swati,
It worked!! by using $(document).on("click","#see_more_comments",function() {
May I know why $('#name').click doesnt work sometimes??

Using span text in where clause in php

This div act as a button. Whenever I click one, the page goes to the page name "teacherinfo.php". The "Sample" text is used as the name of the teacher. The problem is when I click the "Sample2" the Sample text appear on the "teacherinfo.php" page.
Here is the script for going to "teacherinfo.php":
<?php
while ($row = mysqli_fetch_array($query)) {
echo '<div class="announcementSlider" id="click">
<img src="pictures/blank photo.png" class="teacherpic"><br>
<span name="LastName">'.$row['LastName'].'</span><br>
<span>'.$row['Grade'].' - </span>
<span>'.$row['Section'].'</span>
</div>';
}
?>
<script type="text/javascript">
var a = document.getElementsByClassName("announcementSlider");
for (i=0; i<a.length; i++) {
a[i].onclick = function () {
location.href = "teacherinfo.php";
};
}
</script>
Code for displaying the text in "teacherinfo.php":
<div class="leftForm hide-on-med-and-down">
<img src="pictures/default-avatar-250x250.png">
<p class="name"><?php echo $name3; ?></p>
<p class="section"><?php echo $grade3; ?>-<?php echo $section; ?></p>
</div>
Code for retrieving data in database:
$sql3 = mysqli_query($db,"select * from teacherinfo");
$row3 = mysqli_fetch_array($sql3,MYSQLI_ASSOC);
$name3 = $row3['LastName'];
$grade3 = $row3['Grade'];
$section3 = $row3['Section'];
I want to use the "'.$row['LastName'].'" as a where clause in mysqli_query($db,"select * from teacherinfo"). How can I do that? or is there another solution to this issue?
First of all, I don't understand why you use javascript when you can use simple a tag with correct href:
<?php
while ($row = mysqli_fetch_array($query)) {
echo '<a class="announcementSlider" href="teacherinfo.php?id=' . $row['id'] . '">
<img src="pictures/blank photo.png" class="teacherpic"><br>
<span name="LastName">'.$row['LastName'].'</span><br>
<span>'.$row['Grade'].' - </span>
<span>'.$row['Section'].'</span>
</a>';
}
?>
Here, I suppose that every teacher in your mysql-table has some unique id field.
On teacherinfo.php you access id as $_GET['id'] and create a query like (here I skip security part, but $_GET['id'] can be forged and therefore contain some insecure data, you have to check it):
sql3 = mysqli_query($db,"select * from teacherinfo where id = " . $_GET['id']);
$row3 = mysqli_fetch_array($sql3,MYSQLI_ASSOC);
$name3 = $row3['LastName'];
$grade3 = $row3['Grade'];
$section3 = $row3['Section'];

What is the most efficient way to use sidebar menu?

So if I have to make a sidebar menu like schools websites, in which active clicked link is highlighted after the page loads. It uses individual pages like
<a target="_top" href="default.asp">HTML HOME</a>
<a target="_top" href="html_intro.asp">HTML Introduction</a>
<a target="_top" href="html_editors.asp">HTML Editors</a>
<a target="_top" href="html_basic.asp">HTML Basic</a>
<a target="_top" href="html_elements.asp">HTML Elements</a>
But the one I built on my own is created with PHP so what happens in that one is the title or name of menu item is changed to lowercase and saved in database in same row called class which is used for active link highlighting. So what happens when sidebar link is clicked is only content of summary div's content
(which is right to the sidebar) is changed while sidebar and navigation bar stays same. So it stays on the same page and retrieves data from database and puts in summary div.
<body class='noPadding'>
<div class='bigNav'> <!-- top navbar -->
<img src="images/logo2.png"/>
</div>
<?php
if(isset($_GET['subject'])){
$subject=$_GET['subject'];
?>
<div class='container'>
<div class='leftLayout' style='padding-top:70px;background-color:#EBEBEB'>
<ul class="fullFit">
<?php
$query="SELECT * FROM `study` WHERE `subject`='$subject'";
$run=mysqli_query($conn,$query);
while($row=mysqli_fetch_array($run)){
$topic=$row['topic'];
$class=$row['class']; ?>
<li class="<?php echo $class?>">
<a href='<?php echo $sitename ?>/web.php?subject=<?php echo $subject?>&topic=<?php echo $class?>'>
<?php echo $topic?>
</a>
</li>
<?php } ?>
</ul>
</div>
<?php
if(isset($_GET['topic'])) {
$active_id=$_GET['topic'];
$topic=$_GET['topic'];
$query="SELECT summary FROM `study` WHERE `class`='$active_id'";
$run=mysqli_query($conn,$query);
$row=mysqli_fetch_array($run);
$summary=$row[0];
?>
<div class='summary'> <?php echo $summary ?> </div>
<?php } ?>
</div>
<script>
$(document).ready(function(){
$(".<?php echo $active_id ?>").addClass("current");
});
</script>
<?php } ?>
</body>
And also if I have to make individual pages instead like many websites including W3Schools does, do I have to create a new file each time and include navigation bar and sidebar(which are supposed to stay same on every link) in each file?
How do they manage it?
I hope this is not too much of a departure from your current structure.
I don't intend to lead you down a rabbit hole.
That being said, it sounds like you could code everything into a single PHP file. Note that this is just one of many methods, highly dependent the scope of your project and individual coding style.
Databases
subject
`id`
`name`
topic
`id`
`subject_id`
`name`
`summary`
PHP
<?php
// define database functions
function getAllSubjects($conn) {
$sql="SELECT * FROM `subject` WHERE 1;";
$q=$conn->query($sql);
return $q;
}
function getSubject($conn,$subject_id=false) {
$r=false;
if (is_numeric($subject_id)) {
$sql = "SELECT * FROM `subject` WHERE `id`=?;";
$q = $conn->prepare($sql);
$q->bind_param('i',$subject_id);
$q->execute();
$r=$q->fetch_assoc();
}
return $r;
}
function getSubjectTopics($conn,$subject_id=false) {
$q=false;
if (is_numeric($subject_id)) {
$sql = "SELECT * FROM `topic` WHERE `subject_id`=?;";
$q = $conn->prepare($sql);
$q->bind_param('i',$subject_id);
$q->execute();
}
return $q;
}
function getTopic($conn,$topic_id=false) {
$r=false;
if (is_numeric($topic_id)) {
$sql = "SELECT * FROM `topic` WHERE `id`=?;";
$q = $conn->prepare($sql);
$q->bind_param('i',$topic_id);
$q->execute();
$r=$q->fetch_assoc();
}
return $r;
}
// get URL parameters
$subject_id = !empty($_GET['s']) && is_numeric($_GET['s'])
? $_GET['s']
: false;
$topic_id = !empty($_GET['t']) && is_numeric($_GET['t'])
? $_GET['t']
: false;
// fetch all subjects from database
$subjectsQ=getAllSubjects($conn);
// fetch current subject
$thisSubject = $subject_id
? getSubject($conn,$subject_id)
: false;
// fetch current subject topics
$thisSubjectTopicsQ = !empty($thisSubject)
? getSubjectTopics($conn,$subject_id)
: false;
// fetch current topic
$thisTopic = $topic_id
? getTopic($conn,$topic_id)
: false;
// display subject navigation
while($subject = $subjectsQ->fetch_assoc()){
// determine if this subject is selected
$sel = !empty($thisSubject) && $thisSubject['id']==$subject['id']
? true
: false;
// define the URL
$url = '?s='.$subject['id'];
// display nav item for this subject
echo '<a href="' . $url . '"'
. ($sel?' class="sel"' : '')
. '>' . $subject['name']
. '</a>';
}
// if there are subject topics to display...
if ($thisSubjectTopicsQ && $thisSubjectTopicsQ->num_rows > 0) {
// loop through this subject's topics
while($topic=$thisSubjectTopicsQ->fetch_assoc()){
// determine if this topic is selected
$sel = !empty($thisTopic) && $thisTopic['id']==$topic['id']
? true
: false;
// define the URL
$url = '?s='.$thisSubject['id'].'&t='.$topic['id'];
// display nav item for this topic
// (alternate way to display the link)
?><a href="<?=$url?>"<?=$sel?' class="selected"':''?>><?php
echo $topic['name'];
?></a><?php
}
}
// if there is a topic to display
if (!empty($thisTopic)) {
// display topic summary
echo $thisTopic['summary'];
}
That's a basic example. Granted, it doesn't include any of the HTML structure.
It's also possible to join the two tables so that you don't need to do so much fetching. For example, fetching a topic could also return its subject:
$sql="SELECT s.`id` AS `subject_id,
s.`name` AS `subject_name`,
t.`id` AS `topic_id,
t.`name` AS `topic_name`,
t.`summary` AS `topic_summary`
FROM `topic` t
LEFT JOIN `subject` s ON (s.`id`=t.`subject_id`)
WHERE t.`id`=?";

Show results from other page. What is the best method for echoing the results

I used the network developer tool to see if the id is sent to the other page. Which it successfully did. And I can see the other page echo the result but it doesn't show in the modal in the other page even though I have the results.php included in the modal div. Anybody know why this is happening?
itempage.php code:
<div id="globalmodal" class="modal">
<div class="modal-content">
<?php include ("getdata.php");?>
</div>
</div>
results.php code:
if (!empty($_POST["data"])) {
$server = '';
$dbname = '';
$dsn = "mysql:host=".$server.";dbname=".$dbname;
$username = '';
$password = '';
$newdata = $_POST["data"];
$db = new PDO($dsn, $username, $password);
$db -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $db->prepare("SELECT * FROM `eeee` WHERE `id LIKE '%$newdata%' GROUP BY `id`");
$statement->execute();
$row = $statement->fetch(PDO::FETCH_ASSOC);
if($row['id']) {
$pTitle = $row['title'];
echo '<h4>'.$pTitle.'</h4>';
echo "Yes it was received!";
}
}
In the itempage.php the getdata.php is included in the div for the modal. But the modal doesn't show the results in the getdata.php page even though the getdata.php has the right title from the database. But the echo doesn't show in the modal pop up.
There is a small typographical error in the SQL query:
$statement = $db->prepare("SELECT * FROM `eeee` WHERE `id LIKE '%$newdata%' GROUP BY `id`");
It has a missing ``` (it is opened but not closed) for the id used in the like. That causes a SQL error, and the condition that displays the result will never be executed (as $row['id'] will not exist).
As a quick solution, just close it properly like this:
$statement = $db->prepare("SELECT * FROM `eeee` WHERE `id` LIKE '%$newdata%' GROUP BY `id`");
So I fixed it, I had to leave url for $.ajax blank.

Elements not included in div when added using Javascript

I have a list of products on my website a Catalogue. The following PHP Code uses javascript to create a div and insert all the product description links inside it.
$sql = "SELECT * from Products ORDER BY `Name` ASC";
$result = mysqli_query($con, $sql);
echo "<script>document.getElementById('products').innerHTML = '<div class=ks>';</script>";
while($row = mysqli_fetch_assoc($result))
{
$rowid = $row['Id'];
$xx = '<a href="Getdesc.php?hid='.$rowid . '" class=lnk>' . $row['Name'] . '</a><br>';
echo "<script>document.getElementById('products').innerHTML += '$xx';</script>";
}
echo "<script>document.getElementById('products').innerHTML += '</div>';</script>";
Ignore all the ks style sheet class and all the mysql stuff for now.
The problem is it displays the grey backgrounded div (grey from style sheet)
and THEN the links. I need the links to be inside the div.
For a little explanation for those of you who are confused by the pieces of code unrelated to the primary purpose of this question,
The Products table in MySQL is a table that hold all my product info including price, name, id, e.t.c.
the "Getdesc.php?hid=..." link is a link to a php web page that will display all the information about the product from it's Id.
"Products" is an Id of a different div that contains this internal div (With the products I mean) PLUS some other stuff ( I don't feel like telling you all about it).
Sorry for the messy code, thanks in advance.
Javascript:
//from https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
function reqListener () {
document.getElementById('products').innerHTML = this.responseText;
}
var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("get", "yourFile.php", true);
oReq.send();
PHP
$sql = "SELECT <columns> from Products ORDER BY `Name` ASC";
$result = mysqli_query($con, $sql);
echo '<div class="ks">';
while($row = mysqli_fetch_assoc($result))
{
$rowid = $row['Id'];
echo '' . htmlspecialchars($row['Name']) . '<br>';
}
echo '</div>'
why not put everything in a variable :
$html = '<div class="ks">'; // btw you forgot those double-quotes. you html won't evaluate the class if not surrounded by double-quotes
while($row = mysqli_fetch_assoc($result))
{
$rowid = $row['Id'];
$xx = '<a href="Getdesc.php?hid='.$rowid . '" class=lnk>' . $row['Name'] . '</a><br>';
$html.= $xx;
}
$html.= '</div>';
then echo it? if you're using php, then there's no need to change the page with javascript after it's been loaded, you just sent all the remainder of the page to the client, why not directly put this code at the right place?
echo $html;

Categories