I'm trying to have my code add this 2 fields to a form (quantities and products) on a click of a button.
How do I format my script so the innerHTML can include php code?
Or is there another way to add a select element via JS?
newdiv.innerHTML = "<input type='text' name='quantities[]'> <select name='products[]'>
<?php
$sql = mysqli_query($link, "SELECT name FROM inventory");
while ($row = $sql->fetch_assoc()){
echo "<option value=\"".$row['name']."\">" . $row['name'] . "</option>";
}
?>
</select>";
PHP code is interpreted by your server before the page is even sent to the browser. The server then sends a completed html page (no PHP code) across the internet to your browser, which then loads it and then executes the JavaScript in the browser. The PHP interpreter would have no way of reading what the JavaScript changes on the finished page.
You might want to look into making an Ajax call to a PHP page, your PHP page can then contain the sql query and return data the JavaScript can use to add the options.
Related
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.
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.
I have some php that connects to a database and creates a drop down list. I have a specific form in the HTML that I'd like to put the list in.
<body>
<form>
// some text inputs
// where i'd like the drop down to go
<?php makeList(parameter1, parameter2); ?>
// submit button
</form>
<?php
// connect to database
function makeList(arg1, arg2) {
echo '<select>';
while ($row = mysqli_fetch_array($result)){
echo "<option">;
echo $row[$column];
echo "</option>";
echo '</select>';
}
</body>
The only languages I'm allowed to use (apart from the sql) are php, html and javascript. As it is right now, makeList() returns an empty list. When I include opening and closing form tags in the function it returns a fully functional list, but then it acts as it's own form and I need to to be a part of the original form. Thanks.
EDIT: Sorry, forgot to mention the makeList function works fine when called within the php tags. It's when I call it in the HTML that it returns an empty list.
Firstly, you have some syntax issues with your script. It's not a valid HTML file, not a valid PHP file, and not a valid JS file.
If it were up to me, I'd define the PHP function at the stop of my script. Be careful to balance your opening and closing PHP tags. Something like this:
<?php
// connect to database
function makeList($arg1, $arg2) {
echo '<select>';
while ($row = mysqli_fetch_array($result)){
echo "<option">;
echo $row[$column];
echo "</option>";
echo '</select>';
}
?>
And only after that would I start to output my HTML.
Now there are a couple of important things to note about that script I just posted:
the database code is not in here...I don't see any connection or query getting run or anything
In your script, this function doesn't look valid. arg1 and arg2 need a $ in front of each to be a valid PHP function. If it's a JS function you want then well, you are very confused and probably need to go back and figure out why this is not a valid JS function.
Your function refers to a variable, $result, that you have not bothered to define. It is not mentioned anywhere else in your script. It is most certainly not mentioned anywhere inside your function. For $result to be defined inside your function, you either need to pass it in as an array or declare it as a global:
global $result
Your function doesn't return anything at all. It just echoes stuff. This doesn't mean you can't use it, but it does mean that the function has no return value. Echoing the result of makeList won't output anything at all
So after that script above, you might have something like this:
<body>
<form>
// some text inputs
<?php makeList($parameter1, $parameter2); ?>
// submit button
</form>
Depending on what your parameters ($parameter1 and $parameter2) are this should work.
<body>
<form>
// some text inputs
<?php echo makeList($parameter1, $parameter2); ?>
// submit button
</form>
<?php
// connect to database
function makeList($arg1, $arg2) {
echo '<select>';
while ($row = mysqli_fetch_array($result)){
echo "<option>";
echo $row[$column];
echo "</option>";
echo '</select>';
}
</body>
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
?>
$data = mysql_query("SELECT * FROM Table WHERE 1") or die(mysql_error());
while ($info = mysql_fetch_array($data)) {
echo ''.$info['value'].
'<br>';
}
Here the value of sql is showing, my question is how can i add div or other attribute ?
For example
echo '<img src = "'.$info['value'] .'" />'; // Convert into javascript append type
$("#messages").append("<img src='"+ value +"'/>");
I cannot use <?php echo ?> the required data is on other page and i'm using ajax to take into main page but i cannot understand how can append the array data
thanks
Why do you want to append using Javascript?
Why not echo the tags appropriately and include whatever attributes you want?
You can only make that if you use ajax in jQuery.
PHP is executed in server and javascript in client navigator so when jQuery see your page, it see only an html file because the
server send only html file.
You can create your jQuery with echo in PHP but it's a dirty solution.