User input within for loop in PHP - javascript

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.

Related

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.

Auto filling a form and submitting based on a ajax search answer

This problem has been frustrating me for a few days, and as I have found some help here for other problems on my project, it seems that someone could provide insight that I am overlooking.
I admit I am very new to sql, javascript, jquery, ajax, css, and php. I did 3 years of Computer science in college (15 years ago) While coding and logic don't change much, its syntax and handshakes, and where the computing is happening that I have either forgotten, overlooked, or am ignorant.
I have completed an ajax based search submission.
this search displays the target php in a div labeled .Admin
this works excellently.
Its answer is a display of a tree and the nodes above and below the searched node.
I want to make each node in the tree a clickable link to the search results for its own node.
In the php result I coded it to write in a html call to a javascript function and it generates a unique id for each , as well as its own function call. (whether or not that is a good idea its what i tried) I would think that it is then easy to get javascript to fill out the form with the created link using information it knows and resubmit as no refresh is needed to search again. I tried having the php write this script so that it is developed with the page, and I have tried writing the script and including it in the parent page, so that it is already loaded... I'm not sure where it should go or how it should be written.
I may be missing an integral part, or I'm trying to do more than I am supposed to with the code or not completely grasping where the operation is happening and need to rethink it entirely.
I will try to include all relevant code, if its not enough, I will happily add. Thanks in advance.
CallSearch.js
$(document).ready(function() {
$('#Search').submit(function(event) {
$.ajax({
type : 'POST',
url : 'MenuSearch.php',
data : $( this ).serialize()
})
.done(function(results) {
$(".Admin").html(results);
});
event.preventDefault();
});
});
Menu.php (where my search form is)
<script src="/JS/CallSearch.js"></script>
...
<li><a>Search</a> <input type= "text" name="Search" id="search_name" class="search-group">
<ul>
<li><input type="radio" name="Table" id="TableRegion" value="R" class="search-group" checked><label for="TableRegion">Region</label></li>
<li><input type="radio" name="Table" id="TableGrape" value="G" class="search-group"><label for="TableGrape">Grape</label></li>
<li><input type="radio" name="Table" id="TableWine" value="W" class="search-group"><label for="TableWine">Wine</label></li>
<li><button type="submit" id="SubmitSearch">Submit</button></li>
</ul>
</li>
</form>
...
MenuSearch.php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'Webpage');
define('DB_PASSWORD', 'Guest');
define('DB_DATABASE', 'database');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
...
$sqlp ="SELECT * FROM region a JOIN Regionclosure b ON a.idregion=b.parent WHERE b.child= $idReg ORDER BY b.Depth DESC;";
...
$resultp = mysqli_query($db, $sqlp);
$string ="";
while($row = mysqli_fetch_assoc($resultp)){
$Reg = $row["RegName"];
$Parent= $row["Parent"];
echo $string . "|___";
if($_SESSION["Level"] == 'A' or $_SESSION["Level"] == 'C')
echo $Parent . " - ";
echo "<a href='#' id='$Reg'>" . $Reg . "</a><br>";
echo "
<Script>
$('#$Reg').click(function(){ searchforReg('$Reg'); return false; });
</script>";
$string .= " ";
};
I have tried multiple iterations of a function for "searchforReg('$Reg'); to no avail... i feel like it should be something like :
function "searchforReg(Region){
SearchData= "Table=R&Search="+$(Region).val;
(function() {
$.ajax({
type : 'POST',
url : 'MenuSearch.php',
data : SearchData
})
.done(function(results) {
$(".Admin").html(results);
});
event.preventDefault();
});
});
This however results in activating the "action" search failing to send the answer to the and opens the php (with no CSS... gasp.. its just not pretty) I feel like a simple javascript should be able to handle it, but i tried all of the different ways i could think of (or look up) to make it work to no avail.
I realize I am playing in the "deep end," and I'm in my "water wings" so if you could have mercy and push me to the edge, I would appreciate it.
First, the process of printing a click handler for each link is overkill. Instead, just give each link a class and set up a single handler for any link of that class. In menusearch.php:
echo "<a href='#' id='$Reg' class='reg_link'> $Reg </a><br>";
$string .= " ";
Side note - in PHP, if you echo with "double" quotes, variables will be rendered, so no need to concatenate. That's why $Reg is just hanging out. If you echo with 'single' quotes, the string is interpreted literally.
Then in menu.php, we have a bit of javascript:
<script>
/* This is a non-standard listener, bound to the body so that any
dynamically added elements pulled in via ajax, but not in the original document can still be found.
Also, this can be shortened to a single line, but I split it up for clarity.
The single-line version is commented out. */
$(document.body).on('click', '.reg_link', function(){
//searchforReg($(this).attr('id'));
var id = $(this).attr('id'); //get the id of clicked element
searchforReg(id); //trigger function
});
function searchforReg(Region){
var SearchData= "Table=R&Search="+Region;
//If you're not familiar with console.log, it's a huge help in debugging
//console.log('searchData = ', SearchData);
$.ajax({
type : 'POST',
url : 'MenuSearch.php',
data : SearchData
})
.done(function(results) {
$(".Admin").html(results);
});
}
</script>
Finally, I'm guessing you have some $_POST handling in MenuSearch.php for that data, but I don't see that above so I'll assume it's working...

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

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.

Read from XML into editable html textbox, Write back on submit

I'm trying to find a solution to my problem. I've tried multiple sources but haven't found a solid answer. I created an HTML page that has some Javascript and some PHP. I have an XML (or text file) that has user information tags (name, number, Car number, etc.). When I load the webpage, I'd like it to automatically create the fields based on the tags and the data in those tags, so if I need to edit the car number or the driver name I can change it and hit submit. On page reload, the new data is there in a textbox and still editable for the next round.
I've done other things with flat files, but I heard that XML is the right way to go. I'm open to all other suggestions though.
Here is a sample of the XML:
<?xml version="1.0"?>
<RACELANE>
<CARNUMBER>1</CARNUMBER>
<DRIVER>Erick Buque</DRIVER>
<CARMAKE>Nissan</CARMAKE>
<CARMODEL>350Z</CARMODEL>
<YEAR>2011</YEAR>
<CARNUMBER>2</CARNUMBER>
<DRIVER>Sean Smith</DRIVER>
<CARMAKE>Chevy</CARMAKE>
<CARMODEL>Cobalt SS</CARMODEL>
<YEAR>2010</YEAR>
<CARNUMBER>3</CARNUMBER>
<DRIVER>James Abbot</DRIVER>
<CARMAKE>Honda</CARMAKE>
<CARMODEL>Civic si</CARMODEL>
<YEAR>2011</YEAR>
<CARNUMBER>4</CARNUMBER>
<DRIVER>Leigh Summers</DRIVER>
<CARMAKE>Nissan</CARMAKE>
<CARMODEL>Altima R</CARMODEL>
<YEAR>2006</YEAR>
<CARNUMBER>5</CARNUMBER>
<DRIVER>Rick Littleton</DRIVER>
<CARMAKE>Ford</CARMAKE>
<CARMODEL>Mustang</CARMODEL>
<YEAR>2013</YEAR>
</RACELANE>
you can use simpleXML to retrieve data from an xml file
<?php
$xml=simplexml_load_file("data.xml");
foreach($xml->children() as $child)
{
echo $child->getName() . ": <input type='text' name='" . $child->getName() . "' value='" . $child . "'><br>";
}
echo "<input type='submit' name='submit' value='submit'>";
?>
and to save it back put this on the beginning of your php
<?php
$newXML = new SimpleXMLElement("<data></data>");
foreach($_POST as $key => $value) {
if($key != 'submit')
$newXML->addChild($key,$value);
}
$newXML->asXML('data.xml'); //write it back to file
?>

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.

Categories

Resources