Upload file with IFRAME, the file don't get to the server - javascript

Following my code:
HTML:
<form id="test" action="javascript:test()" method="post">
<input name="image" type="file" />
<input type="submit" value="Submit" />
</form>
JS:
function test(){
iframe = document.createElement("IFRAME");
iframe.name = "iframe_upload";
iframe.src="test.php";
document.body.appendChild(iframe);
document.getElementById("test").target = "iframe_upload";
}
PHP:
<?php
if (isset($_FILES["image"])){
echo 'exist';
exit();
}
?>
Where is the error? I'm sure the problem is in javascript, it would be easy to take off without the javascript dynamically create the iframe, but I must use javascript.

there are a couple of problems with that but nothing major,
firstly in order to post files you need to add enctype="multipart/form-data"to your form
seccondly the action of the form should be the file you are posting to (the iframe source) and the javascript should be run from onsubmit
finally you need to give the iframe an id for cross browser support
i end up with this
JS:
function test(){
iframe = document.createElement("IFRAME");
iframe.name = "iframe_upload";
iframe.id = "iframe_upload"; //some browsers target by id not name
document.body.appendChild(iframe);
document.getElementById("test").target = "iframe_upload";
}
HTML:
<form id="test" method="post" target="iframe_upload" enctype="multipart/form-data" onsubmit="javascript:test()" action="test.php">
<input name="image" type="file" />
<input type="submit" value="Submit" />
</form>
PHP:
<?php
print_r($_FILES);
?>

Related

Transform GET request to POST request to load generated PDF file

In an html page I have a button that loads a generated pdf:
<button onclick='getpdf()'>GET PDF</button>
<script>
function getpdf(){
data={
var1: 'var1',
var2: 'var2'
};
window.open('genpdf.php?var1='+data['var1']+'&var2='+data['var2'], '_new');
}
</script>
genpdf.php is something like this:
<?php
require('fpdf/fpdf.php');
$var1 = $_GET['var1'];
$var2 = $_GET['var2'];
$pdf = new PDF();
/* ......... */
$pdf->Output('D','generated.pdf');
?>
My question is:
How can I change my code to pass parameters with POST method?
SOLUTION
ADyson suggested me this solution:
<form id="pdf" action="genpdf.php" methon="POST" target="_new">
<input type="hidden" name="var1" />
<input type="hidden" name="var2" />
<button onclick='getpdf()'>GET PDF</button>
</form>
<script>
function getpdf(){
$("#pdf input[name=var1]").val('var1');
$("#pdf input[name=var2]").val('var2');
$("#pdf").submit();
}
</script>
and
<?php
require('fpdf/fpdf.php');
$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
$pdf = new PDF();
/* ......... */
$pdf->Output('D','generated.pdf');
?>
and it works fine!
BUT
If I wanted to do that without the use of a form, how could I do?
If you want to implement without coding HTML then use following Javascript
var myform = document.createElement('form');
myform.style.display = "none";
myform.name='PdfGenOrSomethingElse';
myform.method='POST';
myform.action='genpdf.php';
myform.target='_blank';
var var1=document.createElement('input');
var1.type='text';
var1.name='var1';
var1.value='Put/update your value';
var var2=document.createElement('input');
var2.type='text';
var2.name='var2';
var2.value='Put/update your value';
myform.appendChild(var1);
myform.appendChild(var2);
document.body.appendChild(myform);
myform.submit();
Notice the form will not be displayed on the page. "display" property is set to "none".
You don't need any javascript function for this. Just use FORM element with action post:
<form action="genpdf.php" method="post" target="_blank">
<input type="text" name="var1" value="" />
<input type="text" name="var2" value="" />
<button type="submit ">GET PDF</button>
</form>
The don't forget to use $_POST instead of $_GET in your PHP script.

PHP, Image preview with javascript and uploader by PHP

I made PHP script to preview an image before upload it, which is simple and easy to read. the first part is to displays the image then to upload it after pressing Submit button.
I have an issue with uploading the image, it doesn't upload.
<?php
if (!empty($_POST["uploadForm"])) {
if (is_uploaded_file($_FILES['userImage']['tmp_name'])) {
$targetPath = "uploads/".$_FILES['userImage']['name'];
if (move_uploaded_file($_FILES['userImage']['tmp_name'], $targetPath)) {
$uploadedImagePath = $targetPath;
}
}
}
?>
<input type="file" accept="image/*" onchange="loadFile(event)">
<img id="userImage" />
<script>
var loadFile = function(event) {
var output = document.getElementById('userImage');
output.src = URL.createObjectURL(event.target.files[0]);
output.onload = function() {URL.revokeObjectURL(output.src) } // free memory
};
</script>
<form id="uploadForm" action="" method="post" enctype="multipart/form-data">
<input type="submit" name="upload" value="Submit" class="btnSubmit">
</form>
You have several logical errors in your PHP Code as well as HTML.
When checking for form submission you have to check if "upload" (name of submit button) is in the $_POST.
The File Upload Input should be inside <form> tag.
Set a name for File Upload field, I have set it to "userImageUpload", so you can access it from $_FILES in PHP.
Here is the final Code:
<?php
if (!empty($_POST["upload"])) {
if (is_uploaded_file($_FILES['userImageUpload']['tmp_name'])) {
$targetPath = "uploads/" . $_FILES['userImageUpload']['name'];
if (move_uploaded_file($_FILES['userImageUpload']['tmp_name'], $targetPath)) {
$uploadedImagePath = $targetPath;
}
}
}
?>
<img id="userImage" />
<script>
var loadFile = function(event) {
var output = document.getElementById('userImage');
output.src = URL.createObjectURL(event.target.files[0]);
output.onload = function() {
URL.revokeObjectURL(output.src)
} // free memory
};
</script>
<form id="uploadForm" action="" method="post" enctype="multipart/form-data">
<input type="file" accept="image/*" onchange="loadFile(event)" name="userImageUpload">
<input type="submit" name="upload" value="Submit" class="btnSubmit">
</form>
Note: Please make sure that "upload" folder is already there and permissions are correct too.
Youve placed the input out of the form, but it should be in it:
<form id="uploadForm" action="" method="post" enctype="multipart/form-data">
<input type="file" accept="image/*" onchange="loadFile(event)">
<input type="submit" name="upload" value="Submit" class="btnSubmit">
</form>

Save textarea data from HTML page to a TXT file

I am building a database server for an organization that I am a member of, and one of the options is that they need to be able to change a list of names. This list is in a txt file located in the webroot.
I have loaded the txt file content in a textarea in an html page, and now what I need to be able to do is to save the textarea content to the same file, in case we need to update or change the names.
I have tried this:
<textarea id="toroq" style="width: 100%; height: 200px;"><?php include("lista_toroq.txt") ?></textarea>
<input id="save_toroq" type="button" value="Save" onclick="WriteToFile();"/>
function WriteToFile()
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var text=document.getElementById("toroq").innerText;
//var fileName=document.getElementById("TextArea2").innerText;
var s = fso.CreateTextFile("lista_toroq.txt", true);
s.WriteLine(text);
s.WriteLine('***********************');
s.Close();
}
the problem is that it is not saving the file
JavaScript is not able to edit or make changes directly to files stored on the web server without having some form of code running.
Using something like this:
<?php
if ($_POST["text"]) {
file_put_contents("file.txt", $_POST["text"]);
}
?>
The above code runs when $_POST["text"] has been set.
Change your HTML form to something like this:
<html>
<body>
<form method="POST">
<textarea name="text tyle="width: 100%; height: 200px;"></textarea>
<input type="submit" value="submit" />
</form>
</body>
</html>
You can store both of these bits of code in one PHP file. The result would be like this:
<?php
if (isset($_POST["text"])) {
$filename = "lista_toroq.txt";
$fileContent = file_get_contents ($filename);
$separator = "***********************";
$new_content = $_POST["text"].$separator.$fileContent
file_put_contents($filename, $new_content);
echo "Text added to file";
}
?>
<html>
<body>
<form method="POST">
<textarea name="text" tyle="width: 100%; height: 200px;"></textarea>
<input type="submit" value="submit" />
</form>
</body>
</html>
You cant write directly from javascript. You have to use PHP to write. You can use file_get_contents to get file content and you can use file_get_contents to write.
You can do something like below with HTML form.
<?php
if (isset($_POST["text"])) {
$filename = "lista_toroq.txt";
$fileContent = file_get_contents ($filename);
$separator = "***********************";
$new_content = $_POST["text"].$separator.$fileContent
file_put_contents($filename, $new_content);
echo "Text added to file";
}
?>

How to use a form data object to send an image from a responsive mobile site to a server

I am updating a website that has a responsive mobile version. A user creates a profile that includes an image. In the browser version, all of the data including an image are uploaded. In the responsive version, all the data except the image are uploaded. It is my understanding from what I've learned on this site and others that I must use a getElementById() and a formData object to get an image from the mobile site to the server. In addition to the resources I've found in StackOverflow, I'm using code by Eric Bidelman of gist.githum.com. After many attempts, I can't get it to work. My formData code does not work, and I'm not sure how to integrate it into the existing code. I appreciate any help with these two problems.
Thanks in advance.
Here is the code I'm working with.
<form id="form" name="form" action="post.php" method="post" onsubmit="return check_inputs();" enctype="multipart/form-data" >
<fieldset>
<legend>About Me</legend>
<label>Email:</label><input data-theme="a" name="email" type="text" value="<?php echo $email?>" maxlength="30" /><span id="s1">*</span>
<label>Image:</label><input data-theme="a" id="image" name="image" type="file" accept="image/*" <?php echo $image?>" size="30" />
xhr.send(FormData).html
</fieldset>
<fieldset>
<input data-theme="a" data-ajax="false" name="submit" class="Submit" type="submit" value="Submit" />
</fieldset>
</form>
post.php
//code to resize image file and send to images folder.
//code to write data to the database.
xhr.send(FormData).html
<script>
document.getElementById('image').addEventListner('change', function(e){
var file = this.files[0];
var fd = new FormData()
fd.append('image', file);
var xhr = new XMLHttpRequest()
xhr.open('POST',handle_file_upload.php, true);
xhr.onload = function(){
if (this.status == 200{
var reso = JSON.parse(this.response);
console.log('Server got:', resp);
var image = document.createElement('img'):
image.src = resp.dataUrl;
document.body.appendChild(image);
};
};
xhr.send(fd);
}, false);
</script>
<!--[if IE]>
<script src = "http:ajax.googleapis.com/ajax/libs/chrome-frame/1/CFInstall.min.js"></script>
<script>CFInstall.check({mode: 'overlay'});</script>
<![endif]-->:
handle_file_upload.php
<?php
$fileName = $_FILES['image']['name'];
$fileType = $_FILES['image']['type'];
$fileContent = file_get_contents($_FILES['image']['tmp_name']);
$dataUrl = 'data:' . $fileType . ';base64,' . base64_encode($fileContent);
$json = json_encode(array(
'name' => $fileName,
'type' => $fileType,
'dataUrl' => $dataUrl,
));
echo $json;
?>
Looks like you have additional double quote.
Make it
<input data-theme="a" id="image" name="image" type="file" accept="image/*" <?php echo $image?> size="30" />
(quotes before size= removed)
Also, why do you need the in there?

javascript and iframe trouble

I'm working with js and html, all client side. I have the following situation... I have an html form (in index.html) that contains some inputs and a submit button. Apart from that, the form contains an iframe tag which refers to another page (other.html) containing other html form. The thing is in this other page called other.html I have a text input (name="info") inside a form tag that saves some info.
Now what I want to do is submit this info's input value with the form of index.html.
Example index.html:
<html>
<body>
<form method="post" action="aphpfile.php">
<input type="text" name="a"/>
<input type="text" name="b"/>
<input type="text" name="c"/>
<iframe id="other1" width="408" height="200" frameborder="0"
scrolling="no" marginheight="0"
marginwidth="0" src="other.html"></iframe>
<input type="submit" value="submit"/>
</form>
</body>
</html>
Example other.html:
<html>
<script type="text/javascript">
function setInfo() {
document.getElementById("info").value = "this is the info";
}
</script>
<body>
<form>
<input type="text" id="info" name="info"/>
</form>
<input type="button" onclick="setInfo();" value="setInfo"/>
</body>
</html>
So from aphpfile.php I want to do this:
$a = $_POST['a'];
$b = $_POST['b'];
$c = $_POST['c'];
$info = $_POST['info'];
echo $a . "," . $b . "," . $c . "," . $info;
Thank you for your help.
SOLVED for many iframes. The following code is written inside a function that is called when the form to aphpfile.php is submitted. I hope someone finds this useful :)
var iframe = document.getElementById('other1');
var innerDoc;
var data;
var name;
var htmlData="";
var i=1;
while(iframe != null)
{
innerDoc = iframe.contentDocument || iframe.contentWindow.document;
data=innerDoc.getElementById("info").value;
name="info"+i;
htmlData+="<input type='hidden' name='"+name+"' value='"+data+"'/>";
i++;
iframe = document.getElementById('other'+i);
}
document.getElementById("hiddens").innerHTML=htmlData;
And ofc there is a
<div id="hiddens"></div>
inside the form in index.html

Categories

Resources