This is almost identical problem which I faced a few days ago. I fixed it then, but now it's not working any more. Well, some of it works.
I'm using AjaxFileUpload Plugin to upload files in my WP plugin. This plugin calls uploader.php to process the upload form.
I am able to get the filename (and other data) using $_FILES['uploadFile'], but I'm not able to retrieve $_POST['current_path'] data.
I have a theory though. When I load the interface to upload data, the hidden input field 'current_path' is empty (as is hould be). As I navigate through my folders, the hidden input field is updated using jQuery.
When I hit the upload button, the Ajax File Upload plugin takes the data in the upload form and passes the data to uploader.php through $_POST and $_FILES.
But why am I able to get data from $_FILES and not from $_POST?
Here is my code:
Javascript
//File upload functions
// Remove feedback message on upload click
jQuery('.uploadImage').live('click',function() {
ajaxFileUpload();
});
(...)
//Lets upload the file by using Ajax uploader plugin
function ajaxFileUpload() {
alert(jQuery('input[type=hidden][name=current_path]').val()) //Shows me the correct current path
jQuery.ajaxFileUpload ( {
url:'../wp-content/plugins/wp-filebrowser/uploader.php',
secureuri:false,
fileElementId:'uploadFile',
dataType: 'json',
success: function (data) {
if(data.error != '') {
alert(data.error);
} else {
alert(data.respons);
}
},
error: function (e) {
jQuery('#uploadOutput').addClass('error').html('Error: ' + e).show();
},
complete: function() {
// Update file list
}
}
)
return false;
}
HTML
<form id="uploadForm" enctype="multipart/form-data" action="" method="POST">
<input type="hidden" id="current_path" name="current_path" value="<?php echo $fb->relative_url; ?>" />
<input id="uploadFile" name="uploadFile" type="file" />
<input type="button" class="button uploadImage" value="<?php _e('Upload File') ?>" /> <br />
</form>
PHP
$this->current_path = $_POST['current_path'];
$this->data['error'] = $_FILES['uploadFile']['name']; //Just for testing
$this->data['respons'] = "Filename: ".$_POST['current_path'];
echo json_encode($this->data);
But why am I able to get data from $_FILES and not from $_POST?
Because you are not submitting the form, only the file input element.
It seems to be the plugin's behaviour by design:
In this hacked version, it submits the specified file type of input element only rather than an entire form
The jQuery form plugin can do both, maybe that helps.
Related
I've been following along with some ajax uploading tutorial and it was working properly.
Here it's how i done,
i created a form in html like this.
<form id="submit_form" action="php-script/test_lates_statusbx-script.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<label>Select Image</label>
<input type="file" name="ui-is-status_is_photo_fl" id="image_file" />
<textarea name="status_is_text_ara"></textarea>
<span class="help-block">Allowed File Type - jpg, jpeg, png, gif</span>
</div>
<input type="submit" name="is_status_forum_btn" class="btn btn-info" value="Upload" />
</form>
<div id="image_preview">
</div>
and here its my ajax code,
$(document).ready(function(){
$('#submit_form').on('submit', function(e){
e.preventDefault();
$.ajax({
url:"php-script/test_lates_statusbx-script.php",
method:"POST",
data:new FormData(this),
contentType:false,
//cache:false,
processData:false,
success:function(data)
{
$('#image_preview').html(data);
$('#image_file').val('');
}
})
});
});
and my php looks like this,
if(isset($_POST['is_status_forum_btn'])){
echo $fileactuname = basename($_FILES['ui-is-status_is_photo_fl']['name']);
echo $textareastatus = htmlspecialchars($_POST['status_is_text_ara']);
}
Problem: When i click the submit buttons it doesnt execute my code. But if i echo something outside of the isset function will does.Where am i wrong ?
A submit button is only a successful control if it is used to submit the form.
You are:
Using the submit button to submit the form
Preventing the default behaviour of the submit event so the form is not submitted
Collecting the data from the form with JavaScript
Making an HTTP request with that data
Since (due to step 2) the submit button is no longer being used to submit the form, it isn't included in the object you create with FormData().
Test for the presence of a different piece of data that you are sending.
e.g.
if(isset($_FILES['ui-is-status_is_photo_fl']))
In your php script, try like this
if (
isset($_FILES['ui-is-status_is_photo_fl']['name']) &&
$_FILES['ui-is-status_is_photo_fl']['error'] == 0
) {
print_r($_FILES);
print_r($_POST);
// Do the required task here
} else {
echo "error";
}
please help me.
I have form like this in index.php
<form id="statusForm" enctype="multipart/form-data" method="post">
<textarea name="statusText" role="textbox" id="wallpost"></textarea>
<input id="photo_input" type="file" name="photo_input" />
<input type="hidden" name="to_id" value="1" >
<button type="button" name="submit" onClick="write_wall_post();">
</form>
<div id="content"></div>
then i have .js file to handle this form
function write_wall_post()
{
var formData = new FormData($("#statusForm")[0]);
$.ajax({
type: "POST",
url: "act_post_status.php",
data: formData,
success: function(data){
$("#wallpost").val("");
$("#photo_input").val('');
var newStatus=data;
$(newStatus).hide().prependTo("#content").fadeIn(2000);
},
processData: false, // tell jQuery not to process the data
contentType: false,
cache:false
});
}
and i have act_post_status.php to process this file submit
<?php
//some configuration
if($_SERVER['REQUEST_METHOD'] == "POST")
{
//some variable declaration and image validation
//Original Image
if(move_uploaded_file($uploadedfile, $path.$time.'.'.$ext))
{
$is_image=1;
}
else
echo "failed";
}
}
//inserting data to database
$status = trim(strip_tags(htmlspecialchars($_POST["statusText"])));
mysql_query("insert into news (status,is_image) values ('$status','$is_image')");
echo "<div class='post'>$status</div>";
?>
the scenario i want is:
when user input data (status), then click submit button, the content automatically show the update (handled by jquery)
but the fact is:
(1) when I completed the form (both status and picture), it works normally.
(2) but when I completed just data form (filling status input only), it was submitted to database successfully, but the content don't update automatically. I should refresh them to get the update.
(3) when i just filling the image input, it works normally like case (1).
Please help why if($_SERVER['REQUEST_METHOD'] == "POST") failed to echo the input by ajax request when data input (status) is blank/empty.
thousands of thanks. :)
I'm not sure why it matters whether you leave the file input unfilled, but you need to disable the normal form submission when you use AJAX. The onclick function should return false to do this.
<button type="button" name="submit" onClick="write_wall_post();return false;">
My goal is to, upon clicking the form submit button, to upload the attachments from the form to the server and show a progress bar of that happening and then submitting the form (ie. mailing the message).
upload_form.php:
<form action="email_message.php" method="post" enctype="multipart/form-data" name="fileform" id="fileform">
<input type="hidden" name="MAX_FILE_SIZE" value="50000000"/>
<input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" value="uploads"/>
<label for="userfile1">Upload a file:</label>
<input type="file" name="userfile1" id="userfile1" class="userfile"/>
<input id="submit_btn" type="submit" value="Send Message"/>
</form>
In the same page, I run the following code to prevent the form from being executed and sending a request to upload all of the files from the form.
$(document).ready(function(){
$("#fileform").submit(function(e){
e.preventDefault();
var self = this;
var formData = new FormData(document.getElementById("fileform"));
var upload_req = $.ajax({
url: "./upload_multiple_files.php",
type: "POST",
data: formData,
processData: false,
contentType: false
});
upload_req.done(function(data){
alert("Uploading complete!");
});
});
});
upload_multiple_files.php:
<?php
session_start();
foreach ($_FILES as $k => $v){
// code to deal with file errors
if (is_uploaded_file($v['tmp_name'])){
// code to rename file
echo "<p>The file was successfully uploaded.</p>";
}else{
echo "<p>The file was not uploaded.</p>";
}
}
?>
All of this works: the files are all uploaded to the server.
The problem I have is integrating PHP Upload Session Progress (http://php.net/manual/en/session.upload-progress.php).
I know I need to use session.upload_progress.name and the $_POST array to get the file upload information but I'm not sure where to place it. I want to create an ajax call with an interval to periodically get the upload progress to be displayed on my form page. However, when I create a new page, the session information is empty. Here is an example of a page I tried:
get_progress.php:
<?php
session_start();
// $key is a combination of session.upload_progress.prefix and session.upload_progress.name
$results = array("content_length" => $_SESSION[$key]['content_length'],
"bytes_processed" => $_SESSION[$key]['bytes_processed']
);
echo json_encode($results);
?>
I checked the session ids from upload_form.php and get_progress.php and they are the same.
Any reason why $_SESSION is empty in get_progress.php? I think I missed something easy but I can't figure it out.
#Perry Your answer is right, session.upload_progress.enabled wasn't enabled in php.ini. Thanks.
I have atleast 50 fields in my html form and I have integrated flash file uploader for multiple file uploading.
Another reason of used for flash file uploader is we can't get filesize before uploading file in IE. for get the file size in IE i used flash.
EAflashuploader integration works successfully.
But my requirement is litle bit different.
In EAflashuploader there is upload button when you click on that all added file uploaded.
But I want to disable this upload button and upload file should be upload when i click on
Html submit button.
In short i want to upload files through submit button in html instead of upload button in flash.
when form submit i can get all the data in post method.
Project link : http://www.triggergmbh.com/EAFUpload/PHP/simpleupload.php
EAFlashUpload link : http://www.easyalgo.com/examples/eaflashupload/simpleupload.aspx
EAFlashUpload Doc link : http://www.easyalgo.com/support/docs/eaflashupload/
Javascript function
function doSendForm() {
EAFlashUpload.uploadFiles();
document.forms["id_form"].submit();
}
HTML code
<div style="width:450px;height:350;background:#EFEFEF;">
<form name="id_form" id="id_form" method="post" style="margin:0px;padding:0px;">
<div id="EAFlashUpload_holder"></div>
<script type="text/javascript" src="EAFUpload/swfobject.js"></script>
<script type="text/javascript">
var params = {
BGcolor: "#ffffff",
wmode: "window"
};
var attributes = {
id: "EAFlashUpload",
name: "EAFlashUpload"
};
var flashvars = new Object();
var uploadUrl = "simpleupload.php";
if (!document.all) {
uploadUrl = "../" + uploadUrl;
}
flashvars["uploader.uploadUrl"] = uploadUrl;
flashvars["viewFile"] = "EAFUpload/TableView.swf";
flashvars["view.uploadButton.visible"] = "false";
swfobject.embedSWF("EAFUpload/EAFUpload.swf", "EAFlashUpload_holder", "450", "350", "10.0.0", "EAFUpload/expressInstall.swf", flashvars, params, attributes);
function EAFlashUpload_onMovieLoad(errors)
{
if(errors != "")
alert(errors);
}
</script>
<p>First name: <input type="text" name="firstname"></p>
<p>Last name: <input type="text" name="lastname"></p>
<input type="submit" id="id_submit" name="submit" value="submit" onClick="doSendForm();" style="padding:10px;font-size:20px;">
</form>
</div>
EAFlashbutton seems to have flexible configuration options and a Javascript API.
You should be able to 1) hide the Flash upload button and 2) trigger the upload externally via Javascript.
1) hiding the button
Buttons have a visible property, so you should be able to hide them with something like this:
flashvars["view.uploadButton.visible"] = "false";
2) Triggering the upload
Use the uploadFiles() method of the Javascript API.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
putting html inside an iframe (using javascript)
I'm using the following code and what I want to do essentially (I'm new to jquery) is submit this form, but then have what is normally outputted on the uploadpic.php page - appear on this page where the form is, in an iframe. I just can't work out how to do it. I added the Jquery Form Plugin - http://www.malsup.com/jquery/form/
So I've gone through the code and commented what it does now. But I've no idea how to add that iframe exchange. Basically the uploadpic.php does this:
$add_one = $membership->add_photo($_POST['photo'], $_POST['caption']);
And if it is all submitted successfully, or if it is a failure, it echos either "sorry your file wasn't uploaded" or "file was uploaded successfully.
How would I stop from having to go to a new page, or resorting to an irritating popup? I thought a temporary iframe would be a good idea - but simply no idea how to implement such a thing.
<div id="uploadform">
<form id = "uploadpicform" enctype="multipart/form-data" action="uploadpic.php" method="POST">
<p>Photo: </p><input type="file" name="photo"><br />
<p>Caption:</p> My <input type="text" name="caption"><br />
<input type="submit" class="large blue button" value="Add">
</form>
<script>
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#uploadpicform').ajaxForm(function() {
$("#hideuploadbutton").hide();
$("#uploadbutton").show();
$("#uploadform").hide();
});
});
</script>
</div>
What that does at the moment, is submits the form, with no notice, hides the upload button and shows an open upload button to start the process again. I figure there must be some sort of 'add iframe' or 'print php variable from the other page' option or something.
I'd appreciate any help, thanks a bunch!
EDITED Added code for populating iframe
HTML
<form id="uploadpicform">
<p>Photo:</p>
<input type="file" name="photo"><br />
<p>Caption:</p>
<input type="text" name="caption"><br />
</form>
<div id="uploadpicbutton" class="bluebutton">Upload</div>
JQuery
// **ADDED** Populate the iframe
function iframeresults() {
var content = phpresults;
var tFrame = document.getElementById("iframeid");
var doc = tFrame.contentDocument;
if (doc == undefined || doc == null)
doc = tFrame.contentWindow.document;
doc.open();
doc.write(content);
doc.close();
}
//Submit Upload Ajax Call Function
function submit_upload() {
$('#status').html('Uploading, Please Wait').fadeIn(500);
$.ajax({
type: "POST",
url: "/uploadpic.php",
cache: false,
data: $('#uploadpicform').serialize(), //This adds the variable name and input values automatically
dataType: "script", // Returns Javascript outputted from PHP page and Launches the Script
success: function(){
iframeresults();
});
}
// Bind the upload function to the button
$('#uploadpicbutton').on('click', submit_upload);
PHP
//Use this echo in your PHP after your PHP Successful validation
echo "var phpresults = 'Upload Succesful'; ";
//Use this echo in your PHP after your PHP Failure validation
echo "var phpresults = 'Upload Failed'; ";