Combine input box and select box to create a search bar - javascript

I have an input box that serves as a search box, and I populate a select box by querying a SQL database. For example, there are two organizations called "Dummy Organization" and "Dummy 2" in my db. So when the user starts typing "du", the select box fills with those two organizations. What I want to do is to combine these two fields: the input box (that acts as the search box) and the select box (which displays the results). My research shows that selectize.js can be useful, but since I'm new to js, I can't figure out how. Can someone please help me? My code is as below:
js that gets the data from the db:
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
$.post("search.php", {searchVal: searchTxt},function(output4){
$("#output4").html(output4);
}
</script>
The form:
<form action="newbrand.php" method="post" id="form">
<br>
Brand Name: <input type="text" name="bname" required /><br><br>
Search for an Organization: <input type="text" required name="search" onkeyup="searchq()" id="output"><br><br>
Selected Organization:
<select id="output4" name="taskOption"></select>
</form>
The search.php file
<?php
include 'db_connect.php';
$link = mysqli_connect($host, $username, $password, $db);
if(!link){
echo "DB Connection error";
}
$output = '' ;
$output2 = '' ;
if (isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
//$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysqli_query($link, "SELECT * FROM `organisations_info` WHERE `Organisation_Name` LIKE '%".$searchq."%' ")or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<option>No results!</option>';
}else{
while($row = mysqli_fetch_array($query)){
$orgname = $row['Organisation_Name'];
$orgid = $row['Organisation_Id'];
$subs = $row['Subscription_Type'];
?>
<option value="<?php echo $orgid; ?>"><?php echo $orgname; ?></option>
<div><?php echo $subs; ?></div>
<?php
} // while
} // else
} // main if
?>

Related

An issue when passing a PHP parameter to a JavaScript function

I the following code, I have a form that consists of three fields and two buttons. In the Review button, I would like to show any word in Arabic randomly and let the user show its translation in English by ticking the Show translation button.
<html>
<body>
<script>
function myFun1(var) {
document.getElementById("demo").innerHTML = "The translation in English is " + var;
}
</script>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$english = $_POST["english"];
$arabic = $_POST["arabic"];
$example = $_POST["example"];
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<textarea name="english" rows="4" cols="70" placeholder="English">English</textarea>
<br>
<textarea name="arabic" rows="4" cols="70" placeholder="Arabic">Arabic</textarea>
<br>
<textarea name="example" rows="4" cols="70" placeholder="Example">Example</textarea>
<br><br>
<input type="submit" name="add" value="Add new">
<input type="submit" name="review" value="Review">
<br>
<p id="demo"></p>
</form>
<?php
$servername = "localhost";
$username = "xxx";
$password = "yyy";
$dbname = "vdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['add'])) {
$sql = "INSERT INTO Vocabulary (English, Arabic, Example)
VALUES ('$english', '$arabic', '$example')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
elseif (isset($_POST['review'])) {
$sql = "SELECT COUNT(ID) as total FROM Vocabulary";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
#echo $row['total'];
$generated = rand(1,$row['total']);
$sql1 = "SELECT * FROM Vocabulary where ID = $generated";
$result1 = $conn->query($sql1);
$row1 = $result1->fetch_assoc();
echo "<br>";
echo $row1['Arabic'];
echo "<br><br>";
$eng = $row1['English'];
echo '<button onClick = "myFun('.$eng.')">Show translation</button>';
}
$conn->close();
?>
</body>
</html>
In the code, the following line creates the button and trigger the myFun1() function:
echo '<button onClick = "myFun('.$eng.')">Show translation</button>';
The problem is when the button is clicked, nothing happens (the message is not shown at all). Any ideas how to fix it?
Firstly change the argument var to some another argument name as var is a keyword in javascript
<script type="text/javascript">
function myFun(as) {
document.getElementById("demo").innerHTML = "The translation in English is " + as;
}
</script>
Secondly, you have to pass the string value in single or double quotes for that use inverted slash \ and rectify the function name from myFun() to myFun1()
echo '<button onClick = "myFun1(\''.$eng.'\')">Show translation</button>';
Rest your code is perfect.
You have definition of function myFun1(var), but you are calling myFun(). I guess this is the problem why there is nothing after clicking on button.
Add this to the top before
< html > tag
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$english = $_POST["english"];
$arabic = $_POST["arabic"];
$example = $_POST["example"];
}
?>

Autocomplete dynamic search SQL database from PHP

I have a search box where search is done through database. In the code I have, the search is done in one input box and the dynamic search output is shown in a text area below it.
What I want is a search like Google, where when the user stars typing, it should show similar items from the db table.
For example, if I have two organizations named "Dummy 1" and "Dummy 2" and the user types in "du", the search bar should show the 2 results and user should be able to select one.
The code I have is:
<form action="newbrand.php" method="post">
<br>
Brand Name: <input type="text" name="bname" /><br><br>
Search for an Organization: <input type="text" name="search" onkeyup="searchq()" id="output"><
Selected Organization:<textarea id="output"></textarea>
</form>
The js is like this:
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
$.post("search.php", {searchVal: searchTxt},function(output){
$("#output").html(output);
}
}
</script>
This is the search.php file:
<?php
include 'db_connect.php';
$link = mysqli_connect($host, $username, $password, $db);
if(!link){
echo "DB Connection error";
}
$output = '' ;
$output2 = '' ;
if (isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
//$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysqli_query($link, "SELECT * FROM `organisations_info` WHERE `Organisation_Name` LIKE '%$searchq%'")or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<div>No results!</div>';
}else{
while($row = mysqli_fetch_array($query)){
$orgname = $row['Organisation_Name'];
$orgid = $row['Organisation_Id'];
$subs = $row['Subscription_Type'];
//$output = echo "<option value='".$orgname."'>" . $orgname . "</option>";
$output = $orgname;
$output2 = $orgid;
$output3 = $subs;
//$output = '<div>'.$orgname.'</div>';
}
}
}
echo ($output);
?>
How can I achieve that?
In the JS code...
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
$.post("search.php", {searchVal: searchTxt},function(output){
$("#output").html(output);
}
}
</script>
you have given the id(#output) of a input type element to display(or to return) the HTML statements and the js script also not closed properly (syntax error).So the valid statement will be...
<form action="newbrand.php" method="post">
<br>
Brand Name: <input type="text" name="bname" /><br><br>
Search for an Organization: <input type="text" name="search" onkeyup="searchq()" id="output"><
Selected Organization:<textarea id="output"></textarea>
</form>
<br>
<div id="mydiv"></div>
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
$.post("search.php", {searchVal: searchTxt},function(output){
$("#mydiv").html(output);
});
}
</script>
Just change your query :
$query = mysqli_query($link, "SELECT * FROM `organisations_info` WHERE `Organisation_Name` LIKE '%".$searchq."%' ")or die("Could not search!");
And the query will work fine :)
Then output the response in HTML in your search.php (manage the css accordingly) :
<?php
include 'db_connect.php';
$link = mysqli_connect($host, $username, $password, $db);
if(!link){
echo "DB Connection error";
}
$output = '' ;
$output2 = '' ;
if (isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
//$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysqli_query($link, "SELECT * FROM `organisations_info` WHERE `Organisation_Name` LIKE '%".$searchq."%' ")or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<div>No results!</div>';
}else{
while($row = mysqli_fetch_array($query)){
$orgname = $row['Organisation_Name'];
$orgid = $row['Organisation_Id'];
$subs = $row['Subscription_Type'];
?>
<div><?php echo $orgname; ?></div>';
<div><?php echo $orgid ; ?></div>';
<div><?php echo $subs ; ?></div>';
<?php
} // while
} // else
} // main if
?>
I hope this is what you required !!

How to post values to database with php from options dynamically created with php

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.

How to Select one of the same name values in one column via input type and then submit button?

What Im trying to do is put one name into a input type box and press submit, once submitted Id like it only to show all the same name rows and NOT all names in database? Can anyone help as I'm trying out or || in the PHP but only getting all results?
<form method="post" action="">
<label for="name">Name:</label>
<input type="text" name="name" id="name" />
<button onclick="refreshMap()">Refresh</button>
</form>
function refreshMap() {
var name = $('#name').val();
}
<script>
$(function() {
$('#name').val(name);
});
</script>
PHP:
$query = "SELECT * FROM register WHERE name IN ('John' || 'Gina')";
$result = mysql_query($query);
if($result === FALSE) {
die(mysql_error());
}
if(!empty($_POST['name']))
{
while($row = mysql_fetch_array($result)){
echo $row['name'];
}
}
EDIT:
$name = htmlspecialchars($_POST['name']);
if(!empty($name))
{
$query = "SELECT * FROM register WHERE name LIKE '" .$name ."'";
$result = mysql_query($query);
if($result === FALSE) {
die(mysql_error());
exit(0);
}
while($row = mysql_fetch_array($result)){
echo $row['name'];
}
}

Get mysql column of a clicked item

I have searched endlessly for an answer but have found none. I am trying to get the id of a clicked item. The item that I am clicking is from mysql database and has been displayed through a for loop. When the item is clicked I am taken to another page. In this page I want to utilize the id from the clicked item to get other information from that row in mysql database; this much I can do. The problem is getting the id from the clicked item and sending it.
This is the most recent way that I tried:
First I displayed the items from mysql.
<?php
$query = "SELECT `video` FROM `challenge_name` ORDER BY `id`";
$result = mysql_query($query);
if($result = mysql_query($query))
{
for($i = 0; $i < mysql_num_rows($result); $i++)
{
$id = $i;
$code = "<div id=\"challenge_preview\"><h7 class=\"challenge_preview_item\"
id=\"challenge_preview_name\"></h7><a href=\"challengeprofile.php\">
<video
class=\"challenge_preview_item\" id=\"challenge_video\"
src=\"".mysql_result($result, $i)."\"></video></a></div>";
echo $code;
}
}
else
{
die('Couldn\'t connect'. mysql_error());
}
?>
Than I put the id in a hidden form so that I could attempt to POST it to the other page:
<form action="<?php echo $current_file; ?>" method="POST">
<input type="hidden" name="id" value="14">
</form>
On the script.php file that is included in both pages, I put
$(#challenge_video).click(function(){ <?php $id = $_POST['id']; ?> ;});
And on the page that the id is being posted to I put
<?php
include 'script.php';
echo getChallengeData('name', 'id', $id)
?>
Please help, Thank you
These are the edits
<div id='challenge_previews'>
<?php
$query = "SELECT `video` FROM `challenge_name` ORDER BY `id`";
$result = mysql_query($query);
if($result = mysql_query($query))
{
for($i = 0; $i < mysql_num_rows($result); $i++)
{
$id = $i;
echo "<div id=\"challenge_preview\"><video class=\"challenge_preview_item challenge_video\" src=\"".mysql_result($result, $i)."\"></video></div>";
}
}
else
{
die('Couldn\'t connect'. mysql_error());
}
?>
<form action="<?php echo $current_file; ?>" method="GET">
<input type="hidden" name="id" value="14">
</form>
</div>
This is the code for page 2
<h1 id="challenge_profile_name">
<?php
$id = substr(base64_decode($_GET['id']),6);
echo getChallengeData('name', 'id', $id);
?>
</h1>
This is the code for the getChallengeData method in the core.inc.php
function getChallengeData($field1, $field2, $field3)
{
$query = "SELECT `$field1` FROM `challenge_name` WHERE `$field2` = '$field3'";
if($query_run = mysql_query($query))
{
if($query_result = mysql_result($query_run, 0, $field1))
{
return $query_result;
}
}
}
That error that I'm getting has to do with the implementation of the getChallengeData method on page 2. The error says
Warning: mysql_result(): Unable to jump to row 0 on MySQL result index 10 in C:\xampp\htdocs\ChallengeNetworkWebsite\core.inc.php on line 42

Categories

Resources