PHP drop down menu, once clicked - php

I have created a drop down menu in php that is displayed however, when a value has been clicked, I don't know how to collect this information.
<html>
<body>
<?php
$mydb = new mysqli('localhost','root','','TestTimeTableSolution');
$rows = $mydb->query("SELECT DISTINCT TeacherID FROM Teacher;")->fetch_all(MYSQLI_ASSOC);
$teachers = array();
foreach ($rows as $row) {
array_push($teachers, $row["TeacherID"]);
}
$dropdownMenu = "<select name='TeacherID' form='Teacher'><option value='Null' selected>All</option>";
foreach ($teachers as $topic) {
$dropdownMenu .= "<option value='" . $topic . "'>" . $topic . "</option>";
}
$dropdownMenu .= "</select>";
echo $dropdownMenu;
?>
</body>
</html>

Based on your last comment, "i want it to be dynamic so as soon as the user clicks on something the relevant information will pop up", it sounds like you will probably want to use Ajax/JavaScript (I will demonstrate a simple jQuery example, notating for clarity):
<?php
$mydb = new mysqli('localhost','root','','TestTimeTableSolution');
?>
<html>
<!-- Add the jQuery library -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
// Act when the document is ready
$(function(){
// listen for the select to change
$('select[name=TeacherID]').on('change',function(){
// Run the ajax – you can also use the shortcut $.post method found at:
// https://api.jquery.com/jquery.post/
$.ajax({
// This is the page that is going to do the data lookup/display action
url: '/lookup.php',
// This is how it's sending the data to that page
type: 'post',
// This is what is being sent ($_POST['submit'] in this case)
data: {
// Use $(this) to isolate the current selected element and get value (.val())
// The value is represented as $topic in your php
'submit': $(this).val()
},
// If all goes well and the page (lookup.php) returns a response
success: function(response) {
// Place the response into the div (see html snippet)
$('#loadspot').text(response);
}
});
});
});
</script>
<body>
<?php
$rows = $mydb->query("SELECT DISTINCT TeacherID FROM Teacher;")->fetch_all(MYSQLI_ASSOC);
$teachers = array();
foreach ($rows as $row) {
array_push($teachers, $row["TeacherID"]);
}
$dropdownMenu = "<select name='TeacherID' form='Teacher'><option value='Null' selected>All</option>";
foreach ($teachers as $topic) {
$dropdownMenu .= "<option value='" . $topic . "'>" . $topic . "</option>";
}
$dropdownMenu .= "</select>";
echo $dropdownMenu;
?>
<!---------------------------------------------->
<!-- THIS IS WHERE THE CONTENT WILL LOAD INTO -->
<!---------------------------------------------->
<div id="loadspot"></div>
</body>
</html>
In order for this to work, you need the page lookup.php in the domain root (you can make it whatever/where ever you want, but you need to match in the javascript url):
/lookup.php
<?php
# This is what will get placed into the parent page <div id="loadspot"></div>
# Do you your php here in place of this line and return whatever "relative information" you want
print_r($_POST);
You should review the jQuery page I have linked to to get more information and direction for that library and make sure you use your browser's developer tools to monitor javascript errors in the console. Ideally, you want to understand all this via the documentation instead of just copy and paste and move on...

Related

Include a PHP page based on URL retrieved from an SQL database using Ajax

I have a page, index.php, with <select> <options> which act as filters. Through Ajax, information is retrieved from an SQL database and echoed into a <div> on the same page. One of the fields that is echoed contains the URL to another page such as a1701.php. Thus far, everything works perfectly.
However, rather than having the URL displayed, I would like the content of the page e.g. a1701.php to be displayed in the same way it would be if I had used <?php include 'a1701.php' ?>.
I have read a lot of posts on SO but haven't found any describing this situation (maybe I am looking for the wrong thing in which case please advise). Following the advice of other partially-related posts, I have tried several things including:
using absolute rather than relative links with $_SERVER['DOCUMENT_ROOT']
include 'a1701.php'; vs echo "<?php include 'a1701.php'; ?>"
using < instead of < etc.
reloading specific <div>s (I haven't actually tried this because I can't figure out what code I would have to put where to make it work.)
I have tried more than one URL and have checked that each one is correct.
index.php
<script>
function filterQuestions() {
var selectCount = document.getElementsByTagName("select").length;
var str = [];
for (var i = 0; i < selectCount; i++) {
if (document.getElementsByTagName("select")[i].value != "") {
str[i] = document.getElementsByTagName("select")[i].name+"="+document.getElementsByTagName("select")[i].value;
}
}
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("questionList").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","filter.php?"+str.join("&"),true);
xmlhttp.send();
}
</script>
<select name="branch" onchange="filterQuestions()">
<option value="All">All branches</option>
<option value="Number">Number</option>
<option value="Trigonometry">Trigonometry</option>
</select>
<select name="topic" onchange="filterQuestions()">
<option value="All">All topics</option>
<option value="sinrule">Sine Rule</option>
<option value="cosrule">Cosine Rule</option>
</select>
filter.php
<?php
$branch = $_GET["branch"];
$topic = $_GET["topic"];
if($branch != "All") {
$wherefilter[] = "branch = '".$branch."'";
}
if($topic != "All") {
$wherefilter[] = "topic = '".$topic."'";
}
$where = join(" AND ", $wherefilter);
if($where != NULL) {
$where = " WHERE $where";
}
mysqli_select_db($link,"generator");
$sql="SELECT question_name, url FROM questions".$where;
$result = mysqli_query($link,$sql);
echo "<table>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['question_name'] . "</td>";
echo "<td>" . $row['url'] . "</td>";
echo "</tr>";
$pagelink = $row['url'] . '.php'; /* URL is correct */
echo"<br>";
echo $pagelink;
echo"<br>";
echo "<?php include '" . $pagelink . "'; ?>";
echo "<br>";
echo "<?php include '" . $pagelink . "'.php; ?>"; /* doesn't work */
include $pagelink; /* doesn't work */
}
echo "</table>";
mysqli_close($link);
?>
a1701.php
contains the content I want included. I have tried including other content too.
Is there a way to achieve what I am after? Am I heading in the right direction?
I can think of 2 ways to accomplish this.
If the PHP file is always on the same server and is part of the web app, just include it. You would have to do some checking and validation to ensure that the file is there etc.
If the URL points to anywhere on the internet, insert it as an iframe.
Solution 1 (everything is local)
Assuming there is some function called getPhpFileName that returns the name of the PHP file. You need the actual name of the php file, not the url pointing to it. The file is read directly from the file system, not through the web server.
$phpFile = getPhpFileName($row['url']);
if ( file_exists($phpFile) ) {
#include $phpFile;
}
example1.php (this is the file to be included)
<div>Hello Example1</div>
Solution 2 (iframe)
In this case, the iframe is returned and the browser will be responsible for getting the output from the url and inserting it on the page.
<iframe src="<?=$row['url']?>"></iframe>

post form to database without leaving the page in a php echoed form

I think I really dug myself a hole here. I have a php file that creates a "notification list" with checkboxes. I want it to work in a way so the user will check the notification he read (in order to clean up his/her list), then the form will submit- by checking, and the 'notification' table in the database will be updated. My problem: it works, but it submits to the notification.php file. I don't want that.
I read several ways to solve it with AJAX but they require the checkboxes id's and as you can see below, The id's are being created by the php...
echo "<form name='noteform' id='noteform' action='notifications.php' method='POST'>";
echo "<ul>";
while($row = mysqli_fetch_array($result)) {
if ($row['type'] == 'group_request') {
echo "<li><input type='checkbox' name='check[]' value='" . $row['id'] . "' onclick='document.noteform.submit()' /><p1>" . $row['text'] . " | Approve? </li>";
}else{
echo "<li><input type='checkbox' name='check[]' value='" . $row['id'] . "' /><p1>" . $row['text'] . "</p1></li>";
}
}
echo "</ul>";
echo "</form>";
$check = isset($_POST['check']) ? $_POST['check'] : array();
foreach($check as $ch) {
$result = mysqli_query($conn, "UPDATE notifications SET `read`=1 WHERE id='$ch'");
}
?>
ps. The if($row['type'] == 'group_request') is just because that's the only notification type i made so far...
You don't have to by any means, but it would make your life a lot easier IMO. Here is a quick solution using jQuery:
$('#noteform').on('submit', function(event){
// Validate or whatever
// Submit
$.ajax({
'type': 'post',
'data': $(this).serialize(),
'url': 'path-to-notification.php',
'timeout': 50000
}).done(function(response) {
// success
}).fail(function(error) {
// error
});
event.preventDefault();
});
EDIT
Let's say you have "index.php", and within that file you have your form:
index.php
<?php
....
<form>
....
</form>
....
?>
Then either in and external .js file, or within index.php inside of a <script> tag, you would have the ajax method(s) above.
Next, you would have notification.php that would handle your form action(s).
notifications.php
if(isset($_POST['check'])
{
// check the value
// handle the form element
}
// sanitize the data
// run your update query
// return success/fail to the javascript
?>
In a nutshell, that's how I would set things up. Hope that helps!

PHP Show/hide link

I have a function that prints out articles from my database and three links Edit , Add , Show/hide.
In the show/hide link i want to be able to hide/show that particular article.
How can i do that?
EDIT: I need to be able to hide/show articles in my backend page and it needs to stay hidden in the frontend page
function displaynews()
{
$data = mysql_query("SELECT * FROM news") // query
or die(mysql_error());
while ($info = mysql_fetch_array($data))
{
$id = $info['id'];
echo "<br>
<a href=Edit.php?id=$id>Edit</a></a>
<a href='addnews.php'> Add </a>
<a href='#'>Show/Hide</a><br><strong>" .
$info['date'] .
"</strong><br>" .
$info['news_content'] .
"<hr><br>"; // Print Articles and Date
}
}
You could use some Javascript and set the style attribute to display:none to hide, then display:block to show it again. Or use jQuery.
Use jquery.
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
</head>
show/hide
<div id="whatever">
Content
</div>
<script>
//Try these too
$('#whatever').hide();
$('#whatever').show();
$('#whatever').toggle();
</script>
Use following code:
PHP Code:
function displaynews()
{
$data = mysql_query("SELECT * FROM news") // query
or die(mysql_error());
while ($info = mysql_fetch_array($data))
{
$id = $info['id'];
echo "<div class="news"><br><a href=Edit.php?id=$id>Edit</a></a><a href='addnews.php'> Add </a><a href=hide.php>Show/Hide</a><br><strong>". $info['date']."</strong><br>". $info['news_content'] . "<hr><br></div>"; // Print Articles and Date
}
}
Javascript/jQuery Code (Don't forget to add jQuery in your page)
<script type="text/javascript">
$(document).ready(function(){
$(".news").click(function(){
$(this).toggle();
});
});
</script>

Working with MySQL and PHP to delete items on page

I am unsure of what path I should take for what I am wanting to do. The page loads some data from a mysql database with php. I made it so that a check box is generated with an incremented value starting wit 0 and so on for every value it finds in the database. What I am wanting to do is have that check box be so that when it is checked and they push the trashcan icon it will delete that row from the database. Where I am unsure is how to go about deleting it on button click and then reload the page. What would be the best way to do this? I am not needing the code or anything I just cant think of the best path to take to accomplish this.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Print Run</title>
<style type="text/css">
.openRun{
width:500px;
}
.openRun th{
text-align:center;
background-color:#CCC;
}
</style>
</head>
<body>
<div>
<?php
$totals = 0;
$i = 0;
$companyName = "";
$quantity = "";
$cardSize = "";
$dateAdded = "";
require("serverInfo.php");
$printRun = mysql_query("SELECT * FROM `printRun` WHERE status = 'Open'");
$row = mysql_fetch_array($printRun);
echo 'Print Run #: ' . $row['Run'];
$result = mysql_query("SELECT * FROM `printRun` WHERE status = 'Open'");
while($row = mysql_fetch_array($result)){
$companyName[$i] = $row['Company'];
$quantity[$i] = $row['Quantity'];
$cardSize[$i] = $row['Size'];
$dateAdded[$i] = $row['Date'];
$totals = intval($row['Quantity']) + $totals;
$i++;
}
$arraySize = count($companyName);
echo '<table class="openRun">';
echo '<tr><th>Company</th><th>Quantity</th><th>Size</th><th>Date Added</th><th></th></tr>';
for($i = 0; $i < $arraySize; $i++){
echo '<tr>';
echo '<td>' . $companyName[$i] . "</td>";
echo '<td>' . $quantity[$i] . "</td>";
echo '<td>' . $cardSize[$i] . "</td>";
echo '<td>' . $dateAdded[$i] . "</td>";
echo '<td><input type="checkbox" name="box'. $i .'" value="'. $i .'" /></td>';
echo '</tr>';
}
echo '<tr>';
echo '<td style="font-weight:bold; border-style:solid; border-top-width:1px;">Totals</td>';
echo '<td style="font-weight:bold; border-style:solid; border-top-width:1px;">' . $totals . "</td>";
echo '<td></td>';
echo '<td></td>';
echo '<td><img src="images/trash.png" /></td>';
echo '</tr>';
echo '</table>';
mysql_close($link);
?>
<br />
</div>
</body>
</html>
There's two ways of doing this. If you're not familiar with AJAX, or are scared about engaging with it, I'd suggest having a quick read of this tutorial just to get an overview.
With AJAX
If you don't want the page to reload, you're going to need to use AJAX to asynchronously send and receive data from the server. A typical example would be:
$('.trash_link').on('click', function() {
$.ajax({
url: 'path/to/script.php',
data: 'variable='+$('.input_class').val(),
dataType: 'html',
success: function(response) {
$('.container').html(response);
}
});
});
The crucial thing I'd advise is to put all of your layout logic in a controller or model function so that you don't repeat yourself. When data is sent to your server it can use this function to send back all your layout via the AJAX function. You can then insert the HTML inside your container element.
Without AJAX
All you do here is submit a form and your page reloads. For that reason you need to make sure you've already specified tags on your page. It really depends on what style you want your page to have - some people prefer reloads, some prefer the seamlessness of AJAX. Here is what you'd need if you chose to omit AJAX:
$('.trash_link').on('click', function() {
$('form').submit();
});
You can also add a pop-up confirmation if you want to:
$('.trash_link').on('click', function() {
if(confirm("Are you REALLY sure?") {
$('form').submit();
}
});
If you have an identifier in the table structure, you can just put
<input type='checkbox' name='ids[]' value='<?php echo $row['id']; ?>' />
Against every line of your table. Wrap the whole table in a form, make a submit button, in your script put something along these lines
if (isset($_POST['ids']) && is_array($_POST['ids'])) {
// some input sanitizing required.
$ids = array();
foreach ($_POST['ids'] as $id) if (intval($id) > 0) $ids[] = intval($id);
// $ids now hold the identifiers for the records to be deleted
if (count($ids)) $query = mysql_query("DELETE FROM `printRun` WHERE id IN (" . implode(', ', $ids) . ")");
// Then make a page refresh via HTTP 303 or otherwise to keep
// to the POST-redirect-GET policy.
header("HTTP/1.1 303 See Other");
header("Location: http://whate.ver/your_page_is.php");
}
If you just want a trash can that when clicked on, reloads the page and deletes the item, then just have that image in a link that passes along the id or whatever unique identifier the row has.
Delete
Have it hit a new php file that handles pulling off the unique identifier and deleting the record, then forwards back to the listing page.
$recordToDelete = is_numeric($_GET['id']) ? $_GET['id'] : null;
if($recordToDelete != null) {
$sql = "DELETE FROM `printRun` WHERE id = " . $recordToDelete;
//execute sql
}
//redirect back to listing page
header('Location: /yourpage.php');

Write to javascript array within php loop

I have a php loop that is echoing out geolocation values. How can I get it to write those values to a javascript array, so I can then use them to plot points on an HTML5 canvas?
The php loop is as follows
<ul id = "geo-list">
<?php foreach($data as $phrase) { ?>
<li><?php
if ($phrase->geo != false) {
echo " | From (";
echo $phrase->geo->coordinates[0];
echo ",";
echo $phrase->geo->coordinates[1];
echo ")";
} else {
echo " | No Location Data";
}
?>
</li>
<?php } ?>
</ul>
Did you try
var myJavascriptData = <?= json_encode($php_data) ?>;
You might want to take advantage of the JSON library for PHP.
The cleanest way to pass data to a browser's javascript program is to put it into a "hidden" html table.
The html should look something like
echo "\n<TABLE style='display: none;' id='DATTAB' >" ;
get_rows();
while ($cf = next_row()) {
echo "\n <TR>";
echo "\n<TD>" . $cf['KEY'] . "</TD>";
echo "\n<TD>" . $cf['COL1'] . "</TD>";
echo "\n<TD>" . $cf['COL2'] . "</TD>";
echo " </TR>";
}
echo "\n</TABLE>";
This table is then easily accessable from your javascript:-
var dtab = document.getElementById("DATATAB");
var rows = dtab.getElementsByTagName("tr");
for (var r = 0; r < rows.length ; r++) {
row = rows[r];
item_key = row.cells[0].innerHTML;
item_col1 = row.cells[1].innerHTML;
item_col2 = row.cells[2].innerHTML;
// do your thing here ......
}
Alternatively you could look at using the AJAX libraries like prototype or dojo
which have the all javascript components for accessing data from a "REST" type service.
You then need to write a separate service which gets the XML or JSON required for your page.
My suggestion is to dump a script block to the output and set them in a variable there.
The array definition will have to actually be in the javascript code that gets output to the page.
e.g., you'll need an output of something like:
<script type="text/javascript">
var coords = new Array(2);
coords[0] = new Array(2);
coords[0][0] = 123.45;
coords[0][1] = 987.65;
coords[1] = new Array(2);
coords[1][0] = 234.56;
coords[1][1] = 876.54;
</script>
There are more efficient ways to create this array statically, but this is just an example.
A more efficient way (in terms of code) would be to build up a string that defined the literal array, then dump out a javascript definition. The output would be something like:
<script type="text/javascript">
var coords = [[123.45,987.65],[234.56,876.54]];
</script>
so in your loop within php, you'd build up a string which would ultimately contain var coords = [[123.45,987.65],[234.56,876.54]]. Outside your loop, you wrap it in the script blocks and output it to the page.

Categories