This question already has answers here:
Reading file contents on the client-side in javascript in various browsers
(5 answers)
Closed 8 years ago.
I am quite knowledgeable in CSS(3) and HTML(5), but my current project allows me to take things further. However, this is completely unknown terrain for me. In my project I have a textarea in which users can submit some XML, which I then parse with jQuery's $.parseXML method. However, I want to add the ability to upload an XML file.
I suppose the upload button would look like this:
<form name="upload-form" action="???" method="???">
<input type="file" name="upload-field">
</form>
However, I do not know what the action and method ought to look like. Because I am staying on the same page and nothing spectacular is supposed to happen, I am guessing the action-attribute can be left out? The method-attribute might be get, rather than post? (1)
And then what? I don't know how I get the data from the uploaded XML document in my jQuery's parser. (2) Also, how to check for the correct file type? Does this have to happen server-side? (3)
action contains the name of the server side script that will receive the form data. when using post, the browser does not parse the content of the input field into the url.
the server side script, e.g. in php will receive the request, do security checks and save the data.
<form name="upload-form" action="serversidescript.php" method="post">
<input type="file" name="upload-field">
<input type="submit" value="Submit">
</form>
serversidescript.php
<pre>
<?php
print_r($_REQUEST); // shows the array containing the form data
leave the method empty and use the post method. Using post for files is important because it has security features and allows you to upload more data.
since it's uploading a file you need to add the enctype, enctype="multipart/form-data" or it won't work
<form name="upload-form" action="" method="post" enctype="multipart/form-data" >
<input type="file" name="upload-field">
<input type="submit" value="Submit">
</form>
ANd then to parse the file, you need to read the xml file using jquery and then write a parser function depending on what you need to do.
//write the custome parse function
function parse(data){
//code for your parse function goes here.
// to append the file to html, I need the actual structure of the file to show you
}
//this reads the xml file using jquery
$.ajax({
url: 'name.xml', // name of file you want to parse
dataType: "xml",
success: parse, //this calls the parse function
error: function(){alert("Error: Something went wrong");}
});
Related
For example I have this line of html within form tags.
<form action="getData.php" method="post">
<div id="imadiv" value="2"></div>
</form>
How would I retrieve the value of the 'value' attribute so that I can use fwrite() to put it on a document using PHP?
Are you parsing html files that have this structure and need to access the value in order to create another document?
If not, then your form handler will have access to the value of "imadiv" (in this example) when you make your post.
if you were do do something like this
<form action="getData.php" method="post">
<input name="inputname" value="2"/>
</form>
and submit that form getData.php could do something like
$valueofinput = $_POST['inputname']
Giving your input tags a name attribute it important to reading the values out of the post payload.
If you're parsing HTML files with forms then I would suggest looking at XML/HTML parsing libraries that will help you access the html as a object node structure.
If you are doing something a little more complex where you want to validate the the data as the use enters, then you'll need to implement an ajax solution. However, keep in mind that connecting the post to key events can get messy as you could end up sending more requests than you originally wanted to if not implemented correctly.
My question is should I convert two html pages to php pages, so the called page can access its POSTed parameters, or is there a way for a called html (.html extension) page to access posted parameters?
I've been reading that because posted parameters are server-side there is no way for JavaScript to do this being client side. I've seen nothing about one html page accessing
parameters if that .html page was accessed via a POST.
Here is my calling form. The called form, needs access to TransDesc (below), which is a text field.
<script type="text/javascript" language="JavaScript1.2">
// Check where we came from so that we can go to the right spot when the
// form gets posted from outside of our HTML tree.
var PostURL = '/event.html';
</script>
Enter a Donation Amount
<script type="text/javascript" language="JavaScript1.2">
document.write(
'<form name="InvGenPayDonation"
action="'+PostURL+'"
onsubmit="return validateForm();"
method=POST>');
</script>
<p> $ <input type='text' name='Amount' value="0.00">
</p>
<p>In honor of <span style="color: #FF0000">
<input type='text' name='TransDesc' id='TransDesc' value="" >
</p>
<input type="submit" value="Next"> <br /><br />
A static HTML file cannot access variables that have been POST'ed to it. It can't even know they're there as they're sent to the server in the HTTP request, the server then deals with them and sends the HTML page in the HTTP response. They're 'consumed' before the page is even sent to the client.
You could use GET and access them via JavaScript, or configure Apache to server .html files as PHP files instead though.
In my opinion, php is the easiest way to go, and as far as languages go is pretty easy to learn and pretty intuitive.
You'll have to either convert them to PHP or use GET instead of POST, as GET parameters are accessible through window.location.href
Yes, I would recommend converting the pages to php. If you are set on using HTML files you will have to edit your htaccess file to run HTML pages as php.
You can always use ajax to retrieve and send post and get values.
You can retrieve it with js by creating a php file and access those with ajax from your html files.
So a form like this:
<form action="/appapi/checkout/" method="post" mimetype="text/xml" enctype="text/xml" name="form1">
<input type="file" name="xmlfile">
<br />
<input type="submit" name="Submit" value="Submit">
</form>
Will pass me a xml file to appapi/checkout/
How can I read this file? Or do I need to save it on my server before I can read it?
Like it has been done here: receive xml file via post in php
I tried to:
$url = 'php://input';
$xml = simplexml_load_file($url);
But wouldnt work out. How can i do this?
I'm not specifically sure that enctype="text/xml" in the <form> element will make the browser to send in the file's content as raw input to the server. One might want to test if that's possible, but I don't know.
However, you could perform a standard file upload with PHPDocs and work on the temporary file that will be automatically created:
$xml = simplexml_load_file($_FILES['xmlfile']['tmp_name']);
This needs the form to have enctype="multipart/form-data". Also it's wise to first check if the file was successfully uploaded by looking into $_FILES['xmlfile']['error'], it is 0 when no error occured:
$upload = (object) $_FILES['xmlfile'];
$xml = $upload->error ? NULL : simplexml_load_file($upload->tmp_name);
BTW, the tempfile will be automatically removed when the PHP script finishes.
First, fix the HTML.
<form> has no mimetype attribute. Remove it.
The enctype attribute does not accept text/xml as a value replace it with multipart/form-data
The name attribute is pointless unless you need to access the form with JavaScript, in which case use an id instead.
Since you are using PHP, the file will then appear in $_FILES[] read it from there.
I have the following form in a file called "foobar.html":
<!-- other stuff -->
<form method="post" action="foo.php?cat=1">
<input type="text" name="bar" />
<input type="submit" value="foobar" name="foobar" />
</form>
<!-- other stuff -->
And I open this file in a php script with fopen, how do I fill out and submit this form without any input from the user? Thanks
Parse out the action attribute with a HTML parser, and use curl to perform a POST to the appropriate target URL.
Read the entire fire into a variable. Rather than using fopen you might want to consider file_get_contents for that, it's a bit cleaner.
You'll then want to parse that string as HTML. You could use PHP's DOMDocument for that. Get the action and method of the form by traversing the DOM tree to the form tag and reading out those attributes. Next get the names of any inputs within the form tags. Use those names to generate a query string with your key=value pairs. If the method of the form is GET, then append that query string to the form action, otherwise save it in another variable.
Finally, use CURL to "submit" the form. That is, use the form action as the URL for a CURL request. If the form method was GET, you should have already appended the data to the URL, if the method was POST, you'll want to set the data for the CURL request to the data query string you generated from the form names.
If your question extend to how to know what data to fill into what form fields, that is pretty much impossible to solve. Certainly there are some input names you could look for and guess the required data but a universal solution is an impossible problem to solve.
Are you trying to have the user submit the form on their browser, without user interaction? If that's the case, you'll need to resort to javascript, something like:
<body onLoad="document.getElementById('autoSubmit').submit();">
<form id="autoSubmit">
(insert form here)
</form>
</body>
This will automatically submit the form. Some notes: not everyone has JavaScript enabled, so you might want to change the inputs to type="hidden", as well as add a nice big submit button that says Click Here.
I am practicing with PHP and AJAX but I have some problems!
I'm trying to get the filename, type, size from a jQuery alert after select an image to upload, but I keep getting an empty string.
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="my_file" />
<input type="submit" name="submit" value="Submit" />
</form>
This form includes a JS file that has an ajax script that asks to a php page the filename of the posted file, but it doesn't work. Do I need to upload the file before I try to get this data?
The JS file:
$("input").change (function () {
$.post("preview_uploader.php", { action:"get_size" }, function (data) {
alert (data);
});
});
The PHP file preview_uploader.php:
<?php
if ($_POST["action"] == "get_test") print "text string test works!";
if ($_POST["action"] == "get_name") print $_FILES["my_file"]["name"];
if ($_POST["action"] == "get_size") print $_FILES["my_file"]["size"];
if ($_POST["action"] == "get_type") print $_FILES["my_file"]["type"];
?>
It works if i make a test with action:"get_test" with php page but it doesn't work with $_FILES["my_file"]["name"] or $_FILES["my_file"]["type"] etc...
Can someone help me find where I am wrong?
Thanks!
Your JS script is sending a separate request to the server and so your PHP is unaware of the file, and $_FILES["my_file"] is not a valid index.
You do not need to go to the server to get the file name, simply use this to get the file name:
$("input[type=file]").val();
I believe it brings back the path as well, so you will need to strip the path off to get the filename.
If you are trying to get all the additional details (filesize, etc) you will either need to upload the file first (which defeats what you are trying to do) or use a Flash + JavaScript combination like these solutions:
Uploadify for jQuery
SWF Upload
You can actually get the size with jQuery. See the answer to this questions:
How to check file input size with jQuery?
You can use the method given to get the name, size, and type. General belief is that its not possible. You can't always believe everything you hear...