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

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
?>

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.

Select file stored on web server and send as attachment in email?

I was hoping someone could help me/guide me in the right direction with this issue.
I want to create a button called "Send File". When this button is clicked, a directory on my web server is opened where multiple PDF files are stored. I must then have the option of selecting multiple files. Once I click "Okay/Confirm", a new mail must be opened on Outlook with the files added as attachments.
So it's basically like adding an attachment on your local computer through Outlook, but the only difference is the "source" of the file is in a directory on my web server.
I hope this question isn't too broad or not specific enough. I have really no idea how to go about this, so any tips are appreciated. I will attempt to write some code but I don't have a clue on how I'd do this.
Here is a quick example:
print_r($_POST['fileName']);
$array = array(
'file1.pdf',
'file2.pdf',
'file3.pdf',
'file4.pdf',
'file5.pdf',
'file6.pdf',
'file7.pdf',
'file8.pdf',
);
echo '<form action="" method="post">';
foreach($array as $file){
echo $file . '<input name="fileName[]" type="checkbox" value="' . $file . '"><br>';
}
echo '<input name="submit" type="submit" value="Submit">';
echo '</form>';
This isn't possible.
There is no way for the browser to tell the user's email client (Outlook or otherwise) to start a new email with specific attachments (no matter what the source of the attachments).
Instead, you could send the email directly from the server.

PHP code in innerHTML

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.

PHP link written into page not being retrieved by a JAVASCRIPT function

I'm writing on a page the following code with PHP. This code creates a A HREF link with the ID equal to $intIdType, which is the value of the PRIMARY KEY in a database, and $count gets the amount of records per category on the database. All of this is inside a WHILE that reads each record and writes on the PAGE the results
echo "<a href='#' id='$intIdType'>";//Starts creating the link
echo "$intIdType -";
echo $arrBusinessTypes["business_Description"];
echo "(";
echo " $count1 )"."</a>";
Now, after the results are on the page it will look like this:
$intIdType $arrBusinessTypes $count
--------------------------------------------
1 -Auto Sales ( 1 )
2 -Auto Repair ( 1 )
5 -Web Desig & I.T. Services( 2 )
6 -Computer Shop ( 1 )
The above result displays each rown as a link where I can click on it, but nothing happens. Even just a simple Alert in javascript does not show up. It seems that it never reaches even the Javascript at all.
What I need now is to retrieve that PHP generated code on the page by a Javascript file, that will allow me to use the hiperlink generated by PHP into the .HTML page
It works if I write directly into the page what PHP is suppose to write. I wonder if this happens because Javascript can not read posted data from PHP into the page.
The Javascript File looks like this:
window.onload=post_result
function post_result() {
$("#1").click(function() { //This is the HREF ID that is written by PHP into the page
$('#list_results').load("results.php");//This seeks to run a PHP file in a DIV
$('.title').text('Listing Categories');//This just replaces the Title in the page
})
I'm just a beginner trying. Thanks for any help.
echo "<a id='$intIdType'>";//Starts creating the link echo "$intIdType -";
echo "$intIdType -";
echo $arrBusinessTypes["business_Description"];
echo "("; echo " $count1 )"."</a>";
just remove href attribute and try
Remark #1: quote custom data when outputs it to HTML:
echo $arrBusinessTypes["business_Description"]; must be
echo htmlspecialchars($arrBusinessTypes["business_Description"]);
Remark #2: you don't need window.onload handler here. In this piece of code you select complex way to do simple thing. Why do not write direct onclick handler? Write function loading some data depending of parameter and do something like:
$htmlspecialchars = function($s){return htmlspecialchars($s);};
echo <<<HTML
<a href='#' id='$intIdType' onclick='loadInfo($intIdType)'>
$intIdType -{$htmlspecialchars($arrBusinessTypes["business_Description"])} ( $count1 )
</a>
HTML;
(converted to heredoc to make HTML more clean)

Categories

Resources