There's a search field in my index which is search in a mysql db.
The result have link with a product ID, so it's clickable.
I want to make a list from the search result elements which i clicked and take it in a form.
So when i have the list i want to submit all of those to another page.
I think the best idea for that is javascript's click event.
Found some js code on the internet, but i can't use it well, because unfortunately i don't have enough knowledge for javascript yet.
What is the simpliest solution?
javascript what i found
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("a").click(function(){
$("ul").append("<li>product name! <a href='javascript:void(0);' class='remove'>×</a></li>");
});
$(document).on("click", "a.remove" , function() {
$(this).parent().remove();
});
});
</script>
search.php
<?php
include './config/functions.php';
dbconn();
$html = '';
$html .= '<div class="result">';
$html .= '<a href="urlString" name="urlString">';
$html .= '<h3>category: <b>nameString</b></h3>';
$html .= '<h4>functionString</h4>';
$html .= '</a>';
$html .= '</div>';
$search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
if (strlen($search_string) >= 2 && $search_string !== '') {
$query = 'SELECT * FROM products WHERE pro_name LIKE "%'.$search_string.'%"';
$result = mysql_query($query);
while($results = mysql_fetch_array($result)) {
$result_array[] = $results;
}
if (isset($result_array)) {
foreach ($result_array as $result) {
$display_function = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['pro_name']);
$display_name = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['pro_category']);
$display_url = "index.php?".urlencode($_GET['mode'])."&send=".urlencode($result['pro_id']);
$output = str_replace('nameString', $display_name, $html);
$output = str_replace('functionString', $display_function, $output);
$output = str_replace('urlString', $display_url, $output);
echo($output);
}
}else{
$output = str_replace('urlString', 'javascript:void(0);', $html);
$output = str_replace('nameString', '<b>No result to show!</b>', $output);
$output = str_replace('functionString', 'Sorry :(', $output);
echo($output);
}
}
?>
search function in index.php
function product_search(){
$html = '<div id="main">
<div class="icon"></div>
<input type="text" id="search" autocomplete="off">
<h4 id="results-text">search key: <b id="search-string"></b></h4>
<ul id="results"></ul>
</div>';
echo $html;
}
Related
Hi,
i am coding a homepage to learn php and javascript. I decided to use a livesearch using jQuery and php.
It is working well ,but i wonder how i can integrate to the found titles an onclick function that will redirect to the viewpost.php so it opens the clicked title and opens the post.
My HTML search part on index page:
<!-- Search Widget -->
<div class="card my-4">
<div class="card bg-success">
<h5 class="card-header">Search</h5>
<div class="card-body">
<div class="search-box">
<input type="text" autocomplete="off" placeholder="Search country..." />
<div class="result"></div>
</div>
</div>
</div>
</div>
jQuery part for livesearch that redirect to php page(backend-search.php)
<script type="text/javascript">
$(document).ready(function(){
$('.search-box input[type="text"]').on("keyup input", function(){
/* Get input value on change */
var inputVal = $(this).val();
var resultDropdown = $(this).siblings(".result");
if(inputVal.length){
$.get("backend-search.php", {term: inputVal}).done(function(data){
// Display the returned data in browser
resultDropdown.html(data);
});
} else{
resultDropdown.empty();
}
});
// Set search input value on click of result item
$(document).on("click", ".result p", function(){
$(this).parents(".search-box").find('input[type="text"]').val($(this).text());
$(this).parent(".result").empty();
});
});
</script>
PHP backend-search.php
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
require_once "pdoconfig.php";
// Attempt search query execution
try{
if(isset($_REQUEST["term"])){
// create prepared statement
$sql = "SELECT * FROM articles WHERE title LIKE :term";
$stmt = $db->prepare($sql);
$term = $_REQUEST["term"] . '%';
// bind parameters to statement
$stmt->bindParam(":term", $term);
// execute the prepared statement
$stmt->execute();
if($stmt->rowCount() > 0){
while($row = $stmt->fetch()){
echo "<p>" . $row["title"] . "</p>";
}
} else{
echo "<p>No matches found</p>";
}
}
} catch(PDOException $e){
die("ERROR: Could not able to execute $sql. " . $e->getMessage());
}
// Close statement
unset($stmt);
// Close connection
unset($db);
?>
That is my table structure called articles:
id title content categorie_id pubdate views short_details
And finally my viewpost.php
<?php
$stmt = $db->prepare('SELECT id, title, text, pubdate FROM articles WHERE id = :id');
$stmt->execute(array(':id' => $_GET['id']));
$row = $stmt->fetch();
//if post does not exists redirect user.
if($row['id'] == ''){
header('Location: ./');
exit;
}
echo "<br>";
echo "<div class='card mb-4'>" . "<div class='card-body'>";
echo "<h2 class='card-title'>";
echo $row['title'] . "</h2>";
echo "<div class='card-footer text-muted'>";
echo $row['pubdate'];
echo "</h2>";
echo "<p class='card-text'>";
echo $row['text'];
echo "</p>";
echo '</div>';
?>
Do i need to get the articles id with the jQuery and somehow post it onclick to viewpost.php ?
I do appreciate all help ..
You Need To Change This PHP "backend-search.php" File :
This Code To
if($stmt->rowCount() > 0)
{
while($row = $stmt->fetch())
{
echo "<p>" . $row["title"] . "</p>";
}
}
else
{
echo "<p>No matches found</p>";
}
This Code
if($stmt->rowCount() > 0)
{
while($row = $stmt->fetch())
{
echo "<p>". $row["title"] . "</p>";
}
}
else
{
echo "<p>No matches found</p>";
}
Used a form to create a php search for a MySQL database in a header.php file.
Attempting to use simplePagination.js with php. I am able to correctly calculate the number of results and display the appropriate amount of page links. However, search.php is not limiting the number of items on the page, and all of the pagination links lead to a blank page.
<form action="search.php" method="POST">
<input type="text" name="search" placeholder="search site">
<button type="submit" name="submit-search"><img src="../assets/search icon-05.png"></button>
</form>
search.php code:
<?php
include 'header.php';
?>
<section class="searchPage">
<div class="searchResults">
<?php
if (isset($_POST['submit-search'])){
$searchTerm = trim( (string) $_POST['search'] );
if (isset( $searchTerm[0] )) {
$search = mysqli_real_escape_string($conn, $_POST['search']);
$sql = "SELECT * FROM articles WHERE title LIKE '%$search%' OR abstract LIKE '%$search%' OR keywords LIKE '%$search%'";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
$limit = 10;
$numberOfPages = ceil($queryResult/$limit);
if ($queryResult > 0){
echo $queryResult . " results found";
while ($row = mysqli_fetch_assoc($result)){
echo "<div class='articleItem'>
<h2>".$row['title']."</h2>
<p>".$row['abstract']."</p>
<a href=".$row['link']." target='_blank'>".$row['link']."</a>
</div>";
}
$pageLinks = "<nav><ul class='pagination'>";
for ($i=1; $i<=$numberOfPages; $i++) {
$pageLinks .= "<li><a href='search.php?page=".$i."'>".$i."</a></li>";
};
echo $pageLinks . "</ul></nav>";
}
else {
echo "There are no results matching your search.";
}
}
}
?>
</div>
</section>
<script type="text/javascript">
$(document).ready(function(){
$('.pagination').pagination({
items: <?php echo $queryResult;?>,
itemsOnPage: <?php echo $limit;?>,
currentPage : <?php echo $page;?>,
hrefTextPrefix : 'search.php?page='
});
});
</script>
You don't need to create the page links on your own, because this is what the plugin does through JavaScript events. So you can replace the ul with a div element. This is the reason why you get a blank page.
echo "<nav><div class='pagination'></div></nav>";
In the following is what I added to make it work:
$(document).ready(function(){
var pageParts = $(".articleItem");
pageParts.slice(<?php echo $limit;?>).hide();
$('.pagination').pagination({
items: <?php echo $queryResult;?>,
itemsOnPage: <?php echo $limit;?>,
onPageClick: function(pageNum) {
var start = <?php echo $limit;?> * (pageNum - 1);
var end = start + <?php echo $limit;?>;
pageParts.hide().slice(start, end).show();
}
});
});
The day names on my site are in English.
How can I get the day names in Russian?
In JavaScript I tried to replace Tuesday->Вторник in code but it is not working.
Code:
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$url = 'http://api.sypexgeo.net/xml/'. $ip .'';
$xml = simplexml_load_string(file_get_contents($url));
$loc_array = array($xml->ip->city->lat,$xml->ip->city->lon);
$loc_safe = array();
foreach($loc_array as $loc){
$loc_safe[] = urlencode($loc);
}
$loc_string=implode(',', $loc_safe);
$json = file_get_contents('http://api.wunderground.com/api/232323***/satellite/webcams/forecast/q/' . $loc_string . '.json');
$obj = json_decode($json, true);
?>
<?
$html .= "</h2><table cellpadding=4 cellspacing=3><tr>";
foreach ($obj['forecast']['simpleforecast']['forecastday'] as $arr) {
$html .= "<td align='center'>" . $arr['date']['weekday'] . "<br />";
$html .= "<img src='http://icons-pe.wxug.com/i/c/k/" . $arr['icon'] . ".gif' border=0 /><br />";
$html .= "<font color='red'>" . $arr['high']['celsius'] . '°C' . " </font>";
$html .= "<font color='blue'>" . $arr['low']['celsius'] . '°C' . "</font>";
$html .= "</td>";
}
$html .= "</tr></table>";
echo $html;
?>
<script type="text/javascript">
window.onload=function(){
//I try, but not replace
$("td:contains('Tuesday')").html("Вторник");
};
</script>
As an option, you can change the call to wunderground API. Include language settings /lang:xy. Something like this:
https://api-ak-aws.wunderground.com/api/8dee7a0******/satellite/webcams/forecast/lang:RU/units:metric/v:2.0/q/CWEW.json
You can try defining a JSON object like:
days = { "name of the day": "name of the day in Russian" }
Then instead of using $arr['date']['weekday'] use days[$arr['date']['weekday']].
Note: I don't know the php syntax actually, but something like that should work.
I have this simple insert query that basically add one row to the db table. but it is not only adding the row but its not redirecting neither. i tried redirecting through javaScript, it gets redirected but still not adding the row. the page is live at:
http://arj-profile.com/public/new_subject.php
(when you go the link click on about widget and then click on add a subject.
i was originally trying this on mamp and i have tried turning on output buffering on php.ini too, still no luck.
any help appreciated. if you need additional information just console log on the above link or let me know i can provide it my entire tables and db as well.
the form page has the following code:
<!-- including functions -->
<?php include("../includes/db_connect.php") ?>
<?php require_once("../includes/functions.php"); ?>
<!-- query -->
<!-- end of query -->
<!-- including header -->
<?php include("../includes/header.php") ?>
<?php find_selected_page();?>
<div class="container-fluid">
<div class="row">
<!-- menu -->
<div class="col-md-3 sidebar">
<?php echo navigation(); ?>
</div>
<!-- body -->
<div class="col-md-9 body">
<form action="create_subject.php" method="post">
<p>Subject name:
<input type="text" name="menu_name" value=""/>
<p>
<p>Position
<select name="position">
<?php
$subject_set = find_all_subjects();
$subject_count = mysqli_num_rows ($subject_set);
for ($count = 1; $count <= ($subject_count + 1); $count++){
echo "<option value=\"{$count}\">{$count}</option>";
}
?>
</select>
</p>
<p>Visible:
<input type="radio" name="visible" value="0" />No
 
<input type="radio" name="visible" value="1" />Yes
</p>
<input type="submit" name="submit" value="Submit">
</p>
<br />
<!-- redirect -->
Cancel
</form>
</div>
</div>
</div>
<!-- footer -->
<?php include("../includes/footer.php") ?>
please try adding but filling out the form, as you see it goes to the following page which actually contains the query but it is not supposed to go there, it should just redirect back to the create_subject.php.
<?php include("../includes/db_connect.php") ?>
<?php require_once("../includes/functions.php"); ?>
<?php
if (isset($_POST['submit'])){
$menu_name = mysqli_prep($_POST["menu_name"]);
$position = (int) $_POST["position"];
$visible = (int) $_POST["visible"];
$menu_name = mysqli_prep($menu_name);
$query = "insert into subjects(";
$query = " menu_name, position, visible";
$query = ") values (";
$query = " '{$menu_name}', {$position}, {$visible}";
$query = ")";
$result = mysqli_query($connection, $query);
if ($result){
$msg = "Subject created";
redirect_to("manage_subject.php");
}
}else {
$msg = "Subject creation failed";
redirect_to("new_subject.php");
}
?>
<?php
if (isset($connection)){mysqli_close($connection); }
?>
in my function.php i have:
<?php
function redirect_to($new_location){
header("Location: " . $new_location);
exit;
}
function mysqli_prep($string){
global $connection;
$escape_string = mysqli_real_escape_string($cnnection, $string);
return $escape_string;
}
function confirm_query($result_set){
if (!$result_set){
die("DB Query Failed");
}
}
function find_all_subjects(){
global $connection;
$query = "select * ";
$query .= "from subjects ";
$query .= "where visible = 1 ";
$query .= "order by position asc";
$subject_set = mysqli_query($connection, $query);
confirm_query($subject_set);
return $subject_set;
}
function find_pages_for_subjects($subject_id){
global $connection;
$safe_subject_id = mysqli_real_escape_string($connection, $subject_id);
$query = "select * ";
$query .= "from pages ";
$query .= "where visible = 1 ";
// an aditional line to relate pages to the subject, subject_id is what rlate two tables together
// dont forget space between lines
$query .= "AND subject_id = {$safe_subject_id} ";
$query .= "order by position asc";
$page_set = mysqli_query($connection, $query);
// the result captured can not be used twice for two different queries
// so result varibale should have unique names
confirm_query($page_set);
return $page_set;
}
function find_subject_by_id($subject_id){
global $connection;
$safe_subject_id = mysqli_real_escape_string($connection, $subject_id);
$query = "select * ";
$query .= "from subjects ";
$query .= "where id = {$safe_subject_id} ";
$query .= "limit 1";
$subject_set = mysqli_query($connection, $query);
confirm_query($subject_set);
if ($subject = mysqli_fetch_assoc($subject_set)){
return $subject;
}else {
return null;
}
}
function find_page_by_id($page_id){
global $connection;
$safe_page_id = mysqli_real_escape_string($connection, $page_id);
$query = "select * ";
$query .= "from pages ";
$query .= "where id = {$safe_page_id} ";
$query .= "limit 1";
$page_set = mysqli_query($connection, $query);
confirm_query($page_set);
if ($page = mysqli_fetch_assoc($page_set)){
return $page;
}else {
return null;
}
}
function find_selected_page(){
global $current_subject;
global $current_page;
if (isset($_GET["subject"])){
$current_subject = find_subject_by_id($_GET["subject"]);
$current_page = null;
} elseif (isset($_GET["page"])){
$current_page = find_page_by_id($_GET["page"]);
$current_subject = null;
} else{
$current_subject = null;
$current_page = null;
}
}
function navigation(){
$output = "<ul>";
$subject_set = find_all_subjects();
while($subject = mysqli_fetch_assoc($subject_set)){
$output .= "<li><a href=\"manage-content.php?subject=";
$output .= urlencode($subject["id"]);
$output .= "\">";
$output .= $subject["menu_name"];
$output .= "</a>";
$page_set = find_pages_for_subjects($subject["id"]);
$output .= "<ul>";
while($page = mysqli_fetch_assoc($page_set)){
$output .= "<li><a href=\"manage-content.php?page=";
$output .= urlencode($page["id"]);
$output .= "\">";
$output .= $page["menu_name"];
$output .= "</a></li>";
}
mysqli_free_result($page_set);
$output .= "</ul></li>";
}
mysqli_free_result($subject_set);
$output .= "</ul>";
return $output;
}
?>
function mysqli_prep( $string ){
global $connection;
return mysqli_real_escape_string( $connection, $string );
}
<?php include("../includes/db_connect.php") ?>
<?php require_once("../includes/functions.php"); ?>
<?php
$redir='new_subject.php';
if ( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['submit'] ) ){
$menu_name = mysqli_prep( $_POST["menu_name"] );
$position = (int) $_POST["position"];
$visible = (int) $_POST["visible"];
$query = "insert into subjects
( menu_name, position, visible )
values
( '{$menu_name}', {$position}, {$visible} )";
$result = mysqli_query( $connection, $query );
if ( $connection ) mysqli_close( $connection );
if( $result ) $redir='manage_subject.php';
}
redirect_to( $redir );
?>
There's a lot of Stack Overflow questions on this topic, but none seem to work for me.
This may be due to the fact that I need a PHP function called when the div is refreshed in order for the information to be updated.
I have a #tab-project-CD-smt_test div that shows three versions (production, staging, and latest). The user can click an arrow next to the staging or latest to move it up the chain. I have this part working fine through the use of an AJAX request:
function sendToStaging (dir, type, subtype, version) {
//Need selected category, selected type, selected subtype
$.ajax({
type: 'POST',
url: 'configs.php',
data: 'function=sendToStaging'+'&dir='+dir+'&type='+type+'&subtype='+subtype+'&version='+version,
success: function() {
// window.location.reload(true);
$('#deployed').load(document.URL);
}
});
};
function sendToProduction (dir, type, subtype, version) {
//Need selected category, selected type, selected subtype
$.ajax({
type: 'POST',
url: 'configs.php',
data: 'function=sendToProduction'+'&dir='+dir+'&type='+type+'&subtype='+subtype+'&version='+version
});
On success, I would like to refresh the #deployed div, which is created in my PHP makeInfoSection. An excerpt of which is below:
// list latest, staging, production
$html .= '<h4>Deployed Versions</h4>';
$html .= '<ul class="list-group" id="deployed">';
$html .= '<li class="list-group-item">';
$html .= '<span class="badge">production</span>';
$html .= $production.'</li>';
$html .= '<li class="list-group-item">';
$html .= '<span class="badge"><span class="glyphicon glyphicon-arrow-up" aria-hidden="true" onclick="sendToProduction('."'$dir', '$type', '$subType', '$staging'".')"></span></span>';
$html .= '<span class="badge">staging</span>';
$html .= $staging.'</li>';
$html .= '<li class="list-group-item">';
$html .= '<span class="badge"><span class="glyphicon glyphicon-arrow-up" aria-hidden="true" onclick="sendToStaging('."'$dir', '$type', '$subType', '$latest'".')"></span></span>';
$html .= '<span class="badge">latest</span>';
$html .= $latest.'</li>';
$html .= '</ul>';
The method is called in the HTML:
<div class="col-md-5 col-md-push-1 col-sm-6">
<div id="tabs" class="tab-content" style="padding:0em 0em 0em 1em">
<?php
foreach ($project_types as $type) {
// #TODO remove once folder structure is all setup
if ($type !== 'CD') continue;
foreach ($project_subtypes[$type] as $subType) {
$html = "<div role ='tabpanel' class='tab-pane'";
$html .= "id='tab-project-".$type."-".$subType."'>";
$html .= makeInfoSection($type, $subType, $project_versions[$subType], $project_dir);
$html .= "</div>";
echo $html;
}
}
foreach ($workflow_types as $type) {
foreach ($workflow_subtypes[$type] as $subType) {
$html = "<div role ='tabpanel' class='tab-pane'";
$html .= "id='tab-workflow-".$type."-".$subType."'>";
$html .= makeInfoSection($type, $subType, $workflow_versions[$subType], $workflow_dir);
$html .= "</div>";
echo $html;
}
}
?>
</div>
</div>
</div>
So upon the success of the AJAX, I need this to be refreshed. I've tried $('#tab-project-CD-smt_test').load(document.URL); but that doesn't seem to do anything. I've also tried calling the makeInfoSection method but that does not add it to the HTML, so I'm not surprised that it didn't work:
$approved_functions = array('sendToProduction', 'sendToLatest', 'sendToStaging');
if(array_key_exists('function', $_POST) && in_array($_POST['function'], $approved_functions)) {
// call the approved function
$dir = $_POST['dir'];
$type = $_POST['type'];
$subType = $_POST['subtype'];
$version = $_POST['version'];
$_POST['function']($dir, $type, $subType, $version);
makeInfoSection($type, $subType, $versions, $dir);
}
Any ideas on how to get this div to refresh?
#tibsar, you mentioned that #deployed isn't unique across your page. While you should try to avoid this, to answer your question, you mentioned that #tab-project-CD-smt_test is unique, so ajax loading that should work for you.
If you'd like to use .load, try this in your success callback:
$('#tab-project-CD-smt_test').load(document.URL + ' #tab-project-CD-smt_test');
Let us know if that works.