HTML,PHP. Change text in textarea cause of checked(change) radio button - javascript

Hello I want change text in textarea on click(change) radio button. I have own database clanok(article) where attributes are nadpis(title) and text. Thanks.
$result = mysqli_query($con,"SELECT * FROM clanok ORDER BY nadpis");
while($row = mysqli_fetch_array($result))
{
?>
<input type="radio" name="nadpis" value="<?php echo $row['nadpis']; ?> ">
<?php
echo $row['nadpis'];
echo "<br>";
}
?>
<textarea name="text" cols="30" rows="5" >
<?php
echo $row['text'];
?>
</textarea>
<br>
<input type="submit" value="Odoslať článok">

First of all, after the page is finished loading, you cannot fetch new stuff from the database and show it on your page (unless you use ajax), so this means that ALL of your rows of text should be loaded and stored somewhere beforehand.
Or, you can use ajax to fetch some new text from the database each time. Both of these solutions would give 2 different types of strain upon your resources.
I'll give you the non-ajax solution, but if you want to hear the ajax one, tell me, and I'll add it here as well. If you want a piece of your website to change upon a click, you can to use javascript to accomplish this. There is also a CSS-only solution based on the current state (selected or not selected) of the radio buttons, but this javascript was easier to write for me. ... so here you go. Solution without ajax, with javascript.
<?php
$radio_button_div_text = ""; //makes a variable to store all the text to be displayed in section 1
$textarea_div_text = ""; //makes a variable to store all the text to be displayed in section 1
$list_of_all_ids_for_js_function = ""; //makes a variable to store something that will later be part of the javascript function
$result = mysqli_query($con,"SELECT * FROM clanok ORDER BY nadpis");
while($row = mysqli_fetch_array($result)) { //while there are rows to get...
//put the different buttons and textareas into two separate variables
$radio_button_div_text += 'input type="radio" name="nadpis" value="'.$row['nadpis'].'" onclick="show_only_one_textarea('.$row['nadpis'].')">';
$radio_button_div_text += $row['nadpis'];
$radio_button_div_text += '<br>';
$textarea_div_text += '<textarea id='.$row['nadpis'].' name="text" cols="30" rows="5" style="display:none;">';
$textarea_div_text += $row['text'];
$textarea_div_text += '</textarea>';
$list_of_all_ids_for_js_function += 'document.getElementById(\''.$row['nadpis'].'\').style.display="none";' }
//now, after you got all the info sorted, show the two areas!
echo $radio_button_div_text;
echo '<br><br>';
echo $textarea_div_text;
?>
<!--now, what you need, is some javascript to make some textareas visible when you click on the corresponding radio button -->
<script>
function show_only_one_textarea(area_id) {
<?php echo $list_of_all_ids_for_js_function; ?>
document.getElementById(area_id).style.display="block"; }
</script>
<!--now, everything will display properly and the javascript will work. here is your submit button -->
<br>
<input type="submit" value="Odoslať článok">
I'm sorry, I didn't test this code out on my own website ... it probably has a nice handful of errors with the ' " quotes. But if you read through it carefully, you will understand the idea of what is trying to be done there. Do you know anything much about javascript? Feel free to ask me more, if you need clarification!
Good luck.

Related

How can I send SQL variable from a HTML table to JS popup and then to PHP variable without jquery? [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 1 year ago.
I'm trying to make software that creates a job board where you can add jobs and maintenance guys can check them off as they go. My problem is getting the request_ID of my table to my SQL query at the bottom in deleteData(). I've tried so much, any tips will be a lot of help.
I have to be making this hard than it needs to be. Im literally just trying to click a button, pop up a form, ask if the user has completed the job, then remove it from the table.
<!DOCTYPE html>
<html>
<head>
<script>
function complete() {
document.getElementById("myForm").style.display = "block";
}
function closeForm() {
document.getElementById("myForm").style.display = "none";
}
</script>
<link rel="stylesheet" href="styles.css">
<title>KCHC Work Orders</title>
</head>
<?php
$host = "localhost";
$user= "";
$password = "";
$database="workorders";
$DBConnect = #new mysqli($host,$user,$password,$database);
if ($DBConnect->connect_error)
echo "The database server is not available at the moment. " .
"Connect Error is " . $DBConnect->connect_errno .
" " . $DBConnect->connect_error . ".";
else{
echo "Connection made";
}
?>
<header>
<div class="menu">
<nav>
Create a Request
</nav>
</div>
</header>
<body>
<?php
$sql = "SELECT request_id, name, date, location, description FROM requests";
$stmt = $DBConnect->query($sql);
if ($stmt->num_rows > 0) {
echo '<div class="request_box">';
echo '<table id="myTable" ><tr><th>ID</th> <th>Name</th> <th>Date</th> <th>Location</th> <th>Description</th> <th>Complete?</th> </tr>';
while (($Row = $stmt->fetch_assoc()))
{
echo "<tr id=";
echo $Row['request_id'] . ">";
echo "<th>" . $Row['request_id'] . "</th> <th>" . $Row['name'] . "</th> <th>" . $Row['date'] . "</th> <th>" . $Row['location'] . "</th> <th>" . $Row['description'] . "</th> <th>" . '<input type="button" onclick="complete()" value="' . $Row["request_id"]. '" />' . "</th></tr>";
}
echo "</table> </div>";
}
else{
echo '<div class="request_error">';
echo "<p> There are no jobs to complete!</p> <br>";
echo "<p> If you think there should be, please contact Matt or his genius son</p>";
echo '</div>';
}
function sendit($i){
$newId = $i;
}
?>
`
<div class="popup" id="myForm" >
<form id="formReal" method="post">
<h1>Would you like to remove this job? </h1>
<input type="submit" class="btn" onclick="" submit="<?php deleteData() ?>" value="Remove from List" />
<button type="button" class="btnCancel" onclick="closeForm()">Cancel</button>
</form>
</div>
</body>
<?php
function deleteData(){
global $DBConnect;
$id_new = $newId;
$sql = "DELETE FROM requests WHERE request_id = 3";
$stmt = $DBConnect->query($sql);
}
?>
You cannot put PHP code inside a javascript event and have it work the way you are intending it to in your code. PHP code is run on the server before the page is sent to the user. PHP can be used to generate javascript code, but PHP cannot be called in-page by javascript. Javascript is run in the browser. If you want javascript code to trigger PHP code, you need to have javascript initiate an HTTP(S) request to a separate PHP script. This can be done either by sending the browser to a new page for that script, or by using AJAX to initiate a background call to that script while keeping the user on the same page. It seems like this latter option is what you are intending.
So what you want here to do this gracefully is the AJAX programming method, which is a whole paradigm of programming that is quite involved; there's no way we could possibly teach you in a single answer. The basic idea is that, in javascript, you need to initiate a request, and then you need event-handling code to listen for the response, do error handling, and then update the HTML on-page to reflect whatever response you got from the script you called.
Then in the PHP script that got called, you put the SQL query to actually delete the appropriate row in the table in the database.
If you look up some basic AJAX tutorials and you feel like you're in over your head, you might want to rethink a simpler way of doing this that is perhaps a bit clunkier or old-fashioned ("Web 1.0") to the user.
You can achieve what you want easily via HTML forms, use a form with action="/path/to/some_script.php" and then send the user to a new page, sending POST variables which are read by the PHP script. And then that page can just redirect back to the original page, displaying a refreshed version of the page after deleting the item. The tradeoff here is that the programming is much easier and less error-prone, and debugging is easier, but you need to send the user around to different pages. So you get less work, but a more clunky user experience.
It's your choice. If I were in your position, and I need to meet a nearby deadline, I would probably put up a quick solution using HTML forms, but I'd start learning AJAX, which is going to take months for you to do well. Then come back and put up a slick AJAX solution when you're ready.

How to keep using the csv data even after the we lose access to the file?

Sorry if the title is confusing. Let me explain.
I have a function which displays the data in a csv file below.
<?php
function readCsv($filename, $header=false) {
$handle = fopen($filename, "r");
echo "<form method='post' action=''>";
echo '<table class="table table-hover table-bordered ">';
if ($header) {
$csvcontents = fgetcsv($handle);
echo '<tr>';
foreach ($csvcontents as $headercolumn) {
echo "
<th> <div class='form-check' style='float: right; position: relative'>
<input class='form-check-input' type='checkbox' id='check$headercolumn' name='check$headercolumn' />
</div>$headercolumn</th>
";
$flag = 0; // show only 5 results from the csv file
while (($csvcontents = fgetcsv($handle)) && $flag < 5) {
$flag++;
echo '<tr>';
foreach ($csvcontents as $column) {
echo "<td>$column</td>";
}
echo '</tr>';
}
echo '</table>';
echo "<button type='submit' id='submitbut' class='btn'>Submit</button>";
echo "</form>";
fclose($handle);
}
And the I call it here:
<form>
<input type='submit' name='csvsubmit' value='Upload File' class="btn">
</form>
<?php if(isset($_POST['csvsubmit'])){
readCsv($_FILES['filename']['tmp_name'] , true);
}?>
Which gives me a table like this
Now to the question:
I want to be able to click on each checkbox and just display the columns selected. The problem is, after the submission, I get the error that the path is empty ( I have lost access to the file).
How can I go around that? how can I make another submit and not lose access to the csv file?
You have two general options:
Handle the manipulation of the table in the front end using javascript
Copy the CSV data somewhere on the back end where you can reference it on subsequent requests
If your only requirement is to show and hide columns, #1 is probably the easiest solution to implement. If you need to do more things with the data later on, or come back to it after the user has left the page after the initial submit, you have to go with #2.
If you do decide to keep the CSV for later use, you will need to use the move_uploaded_file function to move the file to a location where you can read it again later, then set some sort of reference in a hidden field in the HTML (just the file name will work) that can then be relayed back to the server on subsequent requests so the server will know which file to read.
You want to move the files to a directory that is outside of the document root of your web server so that the files are not accessible by HTTP request, which could be a serious security risk.

Advantage in sending a value defined with PHP in a form

EDIT: This code isnt for debugging, it is written only as an example and doesnt need completion as the point of it is just seeing the advantages of using a HIDDEN input in a form to retrieve some value. The answers may also be quick and graphic or metaphorical. I dont want a working code, just the advantages of using each methodology. I also fixed an imaginary condition to the while loop and a value for $record_id and placed them so you can understand.
<?php
if (isset($_POST['delete_action'])) {
$deletedRow = $_POST['row_to_be_deleted'];
mysqli_query($connection, "DELETE FROM table_name WHERE record_id = " . $deletedRow);
//Here is where hidden field value is used
}
$someSQL = "SELECT * FROM comments_tbl WHERE postID=$PostRetrievedID";
while ($someFetch = mysqli_fetch_array($con, $someSQL)) {
$record_id = $someFetch['comment_ID'];
$record_content = $someFetch['comment_Content'];
?>
<span>
<?php echo $record_content; ?>
</span>
<form method="post">
<input type="hidden" name="row_to_be_deleted" value="<?php echo $record_id; ?>"/>
<input type="submit" name="delete_action" value="Delete comment"/>
</form>
<?php
}
?>
If your question is about why hidden fields even exists, then I have to say that they are used on lots of websites for the exact reason you show in the example.
Lots of times, when you have a form and the user submits it, you need some extra data that the user should not see so that you can manage the data the user submitted. Like in you example, one common use is to atach the ID of the row.

javascript lightbox causes error when updating mysql table

I have created a comment-reply system for my blog in php. Comments are stored in a table called comments(comments_id, comment, comment_date, user, flag). I use a script which displays comments and near to each comment there is a link called "delete" in order for the user to delete its own comment in case want to do so.
my php script for displaying comments is :
<?php
// ... above code
$comments .= $row['comment']; // comment printed succesfully here
if($comment_user_id == $session_user_id){
$comments .="<table border='1' style='display:inline-table;'><td><h2><font size='2'>
<form action='deletepost.php' method='post'>
<input type='hidden' name='var' value='$comment_id;'>
<input type='submit' value='delete'>
</form>
</h2></font></td></table>";
}
?>
in order to delete a comment, I update the table comments and set flag=1, so my script will not display comments having their flag=1 in table. In order to do this I use script deletepost.php
<?php
$comment = mysql_real_escape_string($_POST['var']);
if(isset($comment) && !empty($comment)){
mysql_query("UPDATE `comments` SET `flag`=1 WHERE (`user`='$session_user_id' AND `comments_id`='$comment')");
header('Location: wall.php');
}
?>
My script until now works perfect without problem and the user that posts a comment can delete its own comment without any error. The problem started when I decided to insert a lightbox in javascript, so that the user will be asked before deleting a comment. So I have changed my first script to the following:
<?php
// ... above code
$comments .= $row['comment']; // comment printed succesfully here
if($comment_user_id == $session_user_id){
$comments .="<table border='1' style='display:inline-table;'><td><h2><font size='2'>
// at this point problem occurs when inserting javascript lightbox
<a href = javascript:void(0) onclick = document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'><h2><font color=green size=3>Delete All</font></h2></a>
<div id=light class=white_content>DELETE THIS COMMENT?
<form action='deletepost.php' method='post'>
<input type='hidden' name='var' value='$comment_id;'>
<input type='submit' value='delete'>
</form>
<a href = javascript:void(0) onclick = document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none'><div id=pading><button>Cancel</button></div></a></div>
<div id=fade class=black_overlay></div>
</h2></font></td></table>";
}
?>
By using the javascript lightbox as shown above, when the user will press delete, a lightbox starts and asks user if wants to delete the comment. The problem is that now when the user press delete button, it is not deleting the certain comment but the last comment that finds in comments table. Probably there is something else I need to write in my javascript to correct this, in order to know which comment to delete (set its flag to 1). Any idea how to fix it?
Make sure the 'deletepost.php' is getting the correct comment id($comment) that you wanted to delete.
May be that can be the cause.

User input within for loop in PHP

Okay. I NEARLY got it. I'm having a looping issue. I can't get the PHP side to sit still and wait for a user response. I try isset and it still continues on. I'm pasting my code here. Hope that's ok. The excel spreadsheet it's pulling from basically row=4 as your multiple choices, then you choose, it finds the column you chose and goes down a row to ask the next row of questions... I'm sorry guys I know this is noob town but I really appreciate the feedback.
<HTML>
<HEAD>
<title>
</title>
</head>
<body>
<?php
// include class file
include 'Excel/reader.php';
// initialize reader object
$excel = new Spreadsheet_Excel_Reader();
// read spreadsheet data
$excel->read('Question-Flow.xls');
$x = 4; //Row
$y = 0; //Column # 0 for 1st iteration
$questions = array(); //Stores questions and ends in 'STOP'
//Iterates down a row until $cell='SUBMIT'
do {
//Populates $questions() and iterates until $cell='STOP'
do {
$y++;
$cell = isset($excel->sheets[0]['cells'][$x][$y]) ? $excel->sheets[0]['cells'][$x][$y] : '';
if ($cell){
//Populates $questions array with active cells
array_push($questions, $cell);
}
} while ($cell != 'STOP');
for ($i=0; $i < count($questions)-1; $i++){
//echo "<input type=radio name=$i value=\"".$questions[$i]."\">".$questions[$i]."<br>";
?>
<HTML><BODY>
<form action="index.php" method="post">
<input type=submit name=choice value=<?php echo $questions[$i]; ?> style="width: 100px; height: 100px;"><br>
</form>
</BODY></html>
<?php
//Move $cell back one from 'STOP'
$y--;
$cell = isset($excel->sheets[0]['cells'][$x][$y]) ? $excel->sheets[0]['cells'][$x][$y] : '';
$choice = $_POST['choice'];
if(isset($_POST['choice'])){
echo $choice;
echo $cell;
echo $x;
echo $y;
}
}
while($choice != $cell){
//Iterate back to find $choice
$y--;
$cell = isset($excel->sheets[0]['cells'][$x][$y]) ? $excel->sheets[0]['cells'][$x][$y] : '';
}
//Moves to next row of Questions
$x++;
//Populates $cell with 'SUBMIT' or prompts next question
$cell = isset($excel->sheets[0]['cells'][$x][$y]) ? $excel->sheets[0]['cells'][$x][$y] : '';
} while ($cell != 'SUBMIT');
?>
</body>
</html>
I am lost. I'm new to PHP, javascript, HTML so please excuse the dumb question. I've got this array that's been populated with strings from an excel file. The print looks like
Array ( [0] => Question1 [1] => Question2 [2] => Question3 [3] => STOP )
I need to present the user each of those value's as a question and have them choose between them. I then need to loop back around and input new values from excel (this is all done) into that array and come back asking them new questions. I need to store their answer to feed into the excel loop which "cell" they chose. It's like a branching tree of questions.
If I could put some type of input form into the below for loop that would work right? Won't take though.
for ($i=0; $i < count($questions); $i++){
echo $i; //echo'd just to see the count and it's correct
}
Ashish, the relationship between a html form and a php file is built using script parameters. Creating the form on the spot is one step, but the form must send back the answers to a php script that can process the variables sent: in your case, the answers. After that, if all or part of the answers are stored in the parameters you sent to the php script you can copy them all using the for loop.
You need the form (generated by php or static html) with the POST method such as: http://w3schools.com/php/showphp.asp?filename=demo_form_post
And a php script like the welcome demonstration here: http://w3schools.com/php/php_forms.asp
If you use the same script for form generation and for posting (making the field values equal to POST variables you received) it may look a little more interactive. For advanced behaviours you should at least go through w3schools.com brief course on php, html and after that, some javascript.
Use foreach loop as follows
foreach($questions as $qst){
echo "<input type=radio name=q1 value=\"".$qst."\">".$qst."<br>";
}
The user can select a question in terms of radio button.

Categories

Resources