I have a search bar which uses Ajax implementation to search my database and query the input data.view of results generated My question is how do I make the results show up as clickable link so that when clicked they go straight to the view which holds more information about them? I have added the code for database query and the script used for accessing the database based on what was entered by the user in the search box.
<script>
$(document).ready(function() {
$('#search-data').unbind().keyup(function(e) {
var value = $(this).val();
if (value.length>3) {
//alert(99933);
searchData(value);
}
else {
$('#search-result-container').hide();
}
}
);
}
);
function searchData(val){
$('#search-result-container').show();
$('#search-result-container').html('<div><img src="preloader.gif" width="50px;" height="50px"> <span style="font-size: 20px;">Searching...</span></div>');
$.post('controller.php',{
'search-data': val}
, function(data){
if(data != "")
$('#search-result-container').html(data);
else
$('#search-result-container').html("<div class='search-result'>No Result Found...</div>");
}
).fail(function(xhr, ajaxOptions, thrownError) {
//any errors?
alert("There was an error here!");
//alert with HTTP error
}
);
}
</script>
<form>
<div class="manage-accounts" id="users">
<div id="search-box-container" >
<label > Search For Any Event:
</label>
<br>
<br>
<input type="text" id="search-data" name="searchData" placeholder="Search By Event Title (word length should be greater than 3) ..." autocomplete="off" />
</div>
<div id="search-result-container" style="border:solid 1px #BDC7D8;display:none; ">
</div>
</div>
</form>
database query:
<?php
include("fetch.php");
class DOA{
public function dbConnect(){
$dbhost = DB_SERVER; // set the hostname
$dbname = DB_DATABASE ; // set the database name
$dbuser = DB_USERNAME ; // set the mysql username
$dbpass = DB_PASSWORD; // set the mysql password
try {
$dbConnection = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbConnection->exec("set names utf8");
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbConnection;
}
catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
public function searchData($searchVal){
try {
$dbConnection = $this->dbConnect();
$stmt = $dbConnection->prepare("SELECT * FROM events WHERE title like :searchVal");
$val = "%$searchVal%";
$stmt->bindParam(':searchVal', $val , PDO::PARAM_STR);
$stmt->execute();
$Count = $stmt->rowCount();
//echo " Total Records Count : $Count .<br>" ;
$result ="" ;
if ($Count > 0){
while($data=$stmt->fetch(PDO::FETCH_ASSOC)) {
$result = $result .'<div class="search-result">'.$data['title'].'</div>';
}
return $result ;
}
}
catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
}
?>
If all you want is making the search result clickable and browser loads the hyperlink clicked on, just echo the hyperlink from your database or JSON file depends on where they are into the html anchor element such as this:
<?php echo $row['page_title'] ?>
Note: I echoed the page link in the anchor href attribute, that should solve the problem.
You can simply add some code to make a hyperlink into the HTML your PHP is generating:
$result = $result .'<div class="search-result">'.$data['title'].'</div>';
I have made an assumption about the name of your ID field but you can see the pattern you need to use.
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>";
}
I am attempting to submit a form immediately after a selection is made from a drop-down menu. After the form is submitted I want to send a query to a MySQL database based on the selection from the drop-down and display the retrieved text.
Currently, with what I have below, nothing is displayed, no errors are thrown. The JS submit event handler works but after the page reloads the new text is not displayed.
Any help is greatly appreciated.
The JS for submitting the form:
$(".platformSelectDropDown").change(function() {
$('.platformSelectForm').submit();
});
PHP to run after the form is submitted:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$platform = $_POST['platformSelectDropDown'];
$description = call_data($tableName, $platform)['Description'];
$application = call_data($tableName, $platform)['Application'];
}
PHP Function for querying and returning the data:
function call_data($tableName, $col, $platformName) {
include('connection.php');
$sql = 'SELECT * FROM $tableName WHERE platform_name = $platformName';
try {
return $db->query($sql);
}
catch (Exception $e) {
echo "Error! " . $e->getMessage() . "<br/>";
return array();
}
}
The Form:
<form class="platformSelectForm" method="post" action="index.php">
<select name="platformSelectDropDown" class="platformSelectDropDown">
...
</select>
<ul class="indent">
<li><?php echo($description); ?></li>
<li><?php echo($application); ?></li>
</ul>
</form>
I believe the code below will do what you want, with some improvements in security and functionality. However, please note that it's not clear to me from your code where $tableName is being set, so I just hard-coded that to be my test table. I intermingled the php and html, because it made it easier for me to work through the problem and I think it will make it easier for you to follow my solution. There's no reason why you can split it back out and functionize the php portions, similar to your original approach, if you prefer. Check it out:
<html>
<body>
<form class="platformSelectForm" id="platformSelectForm" method="post">
<?php
// Get which dropdown option is selected, if any, so can keep selected on page reload
if(!isset($_POST['platformSelectDropDown'])) {
// Not postback, default to first option ("Select One")
$p0Select = ' selected';
$p1Select = '';
$p2Select = '';
} else {
// Is postback
// Set variables for query below
$tableName = 'tbl_platforms_1';
$platformName = $_POST['platformSelectDropDown'];
// set dropdown selection to whatever was select at form submission
if($platformName == 'Platform_1') {
$p1Select = ' selected';
} elseif ($platformName == 'Platform_2') {
$p2Select = ' selected';
} else {
$p0select = ' selected';
}
}
?>
<select name="platformSelectDropDown" class="platformSelectDropDown" onchange="document.getElementById('platformSelectForm').submit()">
<option value="Select_One"<?php echo $p0Select; ?>>Select One</option>
<option value="Platform_1"<?php echo $p1Select; ?>>Platform 1</option>
<option value="Platform_2"<?php echo $p2Select; ?>>Platform 2</option>
</select>
<?php
// If dropdown value is set and does not equal "Select_One"
if(isset($_POST['platformSelectDropDown'])&& $_POST['platformSelectDropDown'] != 'Select_One') {
?>
<ul class="indent">
<?php
try {
// Set database parameters
// Replace these values with appropriate values for your database
// (okay to use an include like you did originally)
$dbhost = 'your_database_host';
$dbname = 'your_database_name';
$dbuser = 'your_database_user';
$dbpass = 'your_database_user_password';
// Create PDO
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Prepare SQL statement and bind parameters
$stmt = $conn->prepare("SELECT * FROM $tableName WHERE platform_name = :platformName");
$stmt->bindValue(':platformName', $platformName, PDO::PARAM_STR);
// Execute statement and return results in an associative array (e.g., field_name -> value)
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Close Connection
$conn = null;
// For each row that was returned, output results
for ($i = 0; $i < count($results); $i++) {
echo '<li>' .$results[$i]['Description'] .'</li>';
echo '<li>' .$results[$i]['Application'] .'</li>';
}
} catch (Exception $e) {
echo '<li>Error! ' .$e->getMessage() . '</li>';
}
?>
</ul>
<?php
};
?>
</form>
</body>
</html>
Code I used to setup test:
DROP TABLE IF EXISTS tbl_platforms_1;
CREATE TABLE IF NOT EXISTS tbl_platforms_1 (
id int AUTO_INCREMENT NOT NULL,
platform_name varchar(20),
Description varchar(20),
Application varchar(20),
PRIMARY KEY (id)
);
INSERT INTO
tbl_platforms_1
(platform_name, Description, Application)
VALUES
('Platform_1', 'Description 1', 'Application 1'),
('Platform_2', 'Description 2', 'Application 2');
If this solves your problem, please remember to mark as answered, so everyone will know you no longer need help (and so I'll get rewarded for the hour I spent coming up with this solution :-). If this doesn't solve your problem, please provide as much detail as possible as to how the current results differ from your desired results and I will try to revise it to fit your needs. Thanks!
Yep, this old chesnut I'm afraid. I've read through a lot of the previous answers to this question but I cannot get into this if statement even though 'btn-save' is definitely set as the name attribute on my submit button.
I'm using the code from this tutorial to post form data to my database: http://www.phpzag.com/ajax-registration-script-with-php-mysql-and-jquery/
My site structure is like this:
- root
- public_html
- js
app.js
register.php
db_connect.php
form_page.php
My register.php file looks like this and I've added an echo inside the if statement:
<?php
include_once("db_connect.php");
if(isset($_POST['btn-save'])) {
echo "in if";
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email_id = $_POST['email_id'];
$address_1 = $_POST['address_1'];
$address_2 = $_POST['address_2'];
$address_3 = $_POST['address_3'];
$city_town = $_POST['city_town'];
$county = $_POST['county'];
$post_code = $_POST['post_code'];
$entrant_type = $_POST['entrant_type'];
$chosen_store = $_POST['chosen_store'];
$chosen_charity = $_POST['chosen_charity'];
$agree_terms = $_POST['agree_terms'];
$sql = "SELECT user_email FROM tbl_big_challenge_registrations WHERE user_email='$email_id'";
$resultset = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
$row = mysqli_fetch_assoc($resultset);
if(!$row['user_email']){
$sql = "INSERT INTO tbl_big_challenge_registrations('uid', 'first_name', 'last_name', 'user_email', 'address_1', 'address_2', 'address_3', 'town_city', 'county', 'postcode', 'entrant_type', 'crew_store', 'charity', 'agree_terms') VALUES (NULL, '$first_name', '$last_name', '$email_id', '$address_1', '$address_2', '$address_3', '$city_town', '$county', '$post_code', '$entrant_type', '$chosen_store', '$chosen_charity', 'agree_terms', NULL)";
mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn)."qqq".$sql);
echo "registered";
} else {
echo "1";
}
}
?>
My db_connect.php file looks like this (with dummy values for purpose of this post):
<?php
/* Database connection start */
$servername = "servername.com";
$username = "username";
$password = "password";
$dbname = "my_database";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
My form_page.php form looks like this:
<form id="2017-challenge-form" method="post" data-abide>
<!-- form fields are here -->
<input id="btn-submit" type="submit" name="btn-save" value="submit">
</form>
And finally my app.js looks like this:
$('document').ready(function() {
/* handle form submit */
function submitForm() {
var data = $("#2017-challenge-form").serialize();
$.ajax({
type : 'POST',
url : 'register.php',
data : data,
beforeSend: function() {
$("#error").fadeOut();
$("#btn-submit").val('Submitting...');
},
success : function(response) {
if(response==1){
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> Sorry email already taken !</div>');
$("#btn-submit").val('Submit');
});
} else if(response=="registered"){
$("#btn-submit").html('<img src="ajax-loader.gif" /> Signing Up ...');
setTimeout('$(".form-signin").fadeOut(500, function(){ $(".register_container").load("welcome.php"); }); ',3000);
} else {
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> '+data+' !</div>');
$("#btn-submit").val('Submit');
});
}
}
});
return false;
}
$("#2017-challenge-form").submit(function(event){
// cancels the form submission
event.preventDefault();
// jumps into ajax submit function
submitForm();
});
});
I have a breakpoint set just inside the ajax success and on submission of the form I would expect the response to have a value of 'registered' (just like the Demo from the PHPZag site: http://phpzag.com/demo/ajax-registration-script-with-php-mysql-and-jquery/
But I get an empty string:
Can anybody see what I'm doing wrong or am missing?
I changed the input to a button as per the demo site and this worked. As per the comment by #frz3993 the btn-save wasn't getting added to the data so the if(isset($_POST['btn-save'])) was never true as it wasn't finding it.
I'm have trouble resetting a from after submission. Currently I'm relying on auto refreshing the page to. I've never used php but I managed to hack something a php form set up with a MySQL database.
This form is hidden in a div which toggles in and out in visibility. So the webpage acts like a noticeboard the form is on the same page.
I have used a JQuery function to reset the form. But currently the div still displays the echo.
$(document).ready(function() {
$('submit').click(function() {
$('submission')[0].reset();
});
});
My current set up is this:
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc() ) {
$name = addslashes ($_POST['name']);
$proposal = addslashes ($_POST['proposal']);
}else {
$name = $_POST['name'];
$proposal = $_POST['proposal'];
}
$email = $_POST['email'];
$sql = "INSERT INTO mvmv3". "(name, proposal, email, join_date )
VALUES('$name','$proposal','$email', NOW())";
mysql_select_db('mvmv_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
}else {
?>
<form name="submission" method = "post" action = "<?php $_PHP_SELF ?>" >
<fieldset>
<input name = "name" type = "text"
id = "name" required autocomplete="off">
<input name = "email" type = "text"
id = "email" autocomplete="off">
<textarea name = "proposal" type = "textarea" size="100"cols="40" rows="20"
id = "proposal" placeholder="Your proposal goes here..." required autocomplete="off"></textarea>
</fieldset>
<fieldset>
<input name = "add" type = "submit" id = "add" value = "Submit">
</fieldset>
</form>
<?php
}
?>
What is the best way to go about this? Could I perhaps make the echo disappear after 4 seconds?
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc() ) {
$name = addslashes ($_POST['name']);
$proposal = addslashes ($_POST['proposal']);
}else {
$name = $_POST['name'];
$proposal = $_POST['proposal'];
}
$email = $_POST['email'];
$sql = "INSERT INTO mvmv3". "(name, proposal, email, join_date )
VALUES('$name','$proposal','$email', NOW())";
mysql_select_db('mvmv_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
// WRAP THE "ECHOED" OUTPUT IN A DIV ELEMENT (WITH CLASS &/OR ID)
// SO YOU CAN EASILY REFERENCE IT IN JS
echo "<div class='msg-box' id='msg-box'>Entered data successfully</div>\n";
mysql_close($conn);
}else {
}
JAVASCRIPT
$(document).ready(function() {
$('submit').click(function() {
$('submission')[0].reset();
// FADE-OUT THE DIV 3 SECONDS AFTER CLICKING THE BUTTON USING window.setTimeout...
// THIS ASSUMES THAT YOUR FORM IS NOT SUBMITTING NORMALLY (AJAX OR SO)
/*
setTimeout(
function(){
$("#msg-box").fadeOut(500);
},
3000);
*/
});
// FADE-OUT THE DIV 3 SECONDS AFTER PROCESSING THE FORM-DATA USING window.setTimeout...
// THIS ASSUMES THAT YOUR FORM HAS SUBMITTED NORMALLY (VIA POST OR GET)
// AND THE MESSAGE IS DISPLAYED BY PHP AFTER PROCESSING...
setTimeout(
function(){
$("#msg-box").fadeOut(500);
},
3000);
});
Use something like
$('input').val('');
to clear all you input fields
Sorry for the obtuse title not quite sure how to describe this one. I have options that are dynamically created through a call to a database with php. The dropdown list options are set like this:
<div class="input-group col-md-12"><span class="input-group-addon">Tag Source</span>
<select class="form-control" name="tagtype" value="<?php echo addslashes($_POST['tagtype']); ?>">
<option value="">Tag Source</option>
<?php
foreach ($sources as $row) {
?>
<option value="'".<?php $row['sources']; ?>."'"><?php echo $row['sources']; ?></option>
<?php
}
?>
When I update the database I thought it would update the value to what I have set it as with php:
<option value="'".<?php $row['sources']; ?>."'">
But instead it does not update the database properly. My guess is that I have to write a javascript function to set the value to post to the db but would welcome any instruction!
EDIT: This is how I update the database
$conn = new mysqli(intentionally left blank);
include('login.php');
if($_POST['submit']) {
if ($_POST['tagname']=="") $error.="<br />Please enter a tag name!";
if ($_POST['tagtype']=="") $error.="<br />Please enter a tag type!";
if ($_POST['url']=="") $error.="<br />Please enter a tag URL!";
if ($_POST['publisher']=="") $error.="<br />Please enter a publisher!";
if ($_POST['advertiser']=="") $error.="<br />Please enter an advertiser!";
if ($_POST['identifier']=="") $error.="<br />Please enter an ID!";
if ($_POST['ecpm']=="") $error.="<br />Please enter the eCPM rate!";
if ($_POST['ccpm']=="") $error.="<br />Please enter the eCPM rate!";
if ($_POST['datebrokered']=="") $error.="<br />Please enter the date brokered!";
else {
if (mysqli_connect_error()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$identifier = $_POST['identifier'];
$sql = "SELECT unique_id FROM jpctags WHERE identifier=?";
$stmt = $conn -> prepare($sql);
$stmt -> bind_param('s',$identifier);
$stmt -> execute();
$stmt -> store_result();
$stmt -> bind_result($uniqueid);
$stmt -> fetch();
if ($uniqueid) $error = "This tag already exits within the system, please edit the tag instead.";
else {
$tagname = $_POST['tagname'];
$tagtype = $_POST['tagtype'];
$identifier = $_POST['identifier'];
$url = $_POST['url'];
$publisher = $_POST['publisher'];
$advertiser = $_POST['advertiser'];
$ecpm = $_POST['ecpm'];
$ccpm = $_POST['ccpm'];
$datebrokered = $_POST['datebrokered'];
$sql = "INSERT INTO jpctags (`tagname`, `tagtype`, `identifier`, `url`, `publisher`, `advertiser`, `ecpm`, `ccpm`, `datebrokered`, `user_id`) VALUES(?,?,?,?,?,?,?,?,?,?)";
$stmt = $conn -> prepare($sql);
$stmt -> bind_param('ssssssiisi',$tagname, $tagtype, $identifier, $url, $publisher, $advertiser, $ecpm, $ccpm, $datebrokered, $user_id);
$stmt -> execute();
}
}
}
You are just returning the row from your tables as values to your option. You should actually echo them:
<option value="<?php echo $row['sources']; ?>">
You need the form to POST to a php script to update the db.
Check out php form handling here: http://www.w3schools.com/php/php_forms.asp
Make sure to handle the input properly (i.e. escape the input with http://php.net/manual/en/mysqli.real-escape-string.php) because a user could edit the <select> dropdown values and execute a SQL injection.