I'm trying to upload an image by submitting form. Following is my code snippet:
html:
<form method="POST" id="statusform" action="insertstatus.php" enctype="multipart/form-data">
<textarea name="statusText" onclick="javascript:this.value='';" class="retroText" style="width:600px;height:100px;font-family:lucida sans unicode,lucida grande,sans-serif;resize:none;padding:5px;">Post your crap here ...</textarea>
<input type="file" name="statusPhoto" accept="image/gif, image/jpeg, image/x-ms-bmp, image/x-png" size="26" />
</form>
jquery:
$("#statusform").submit(function() {
$.post($("#statusform").attr("action"), $("#statusform").serialize(), function(data){
alert(data);
});
//Important. Stop the normal POST
return false;
});
php:
if(isset($_FILES['statusPhoto']) && $_FILES['statusPhoto']['size'] > 0)
{
<Image Upload Code>
}
else
echo "Photo not submitted";
The message returned from ajax is: Photo not submitted.
Please help..!!
You are uploading, not the image, you uploading it name.
$("#statusform").serialize() return a string, image is a blob. Try to use some jQuery plugins, for example.
You can upload file asynchronously by iframe as described in article:
http://viralpatel.net/blogs/ajax-style-file-uploading-using-hidden-iframe/
Related
I am trying to get image file name by tag, But when I check it through isset($_FILES['imgFile']), it returns always false.
Here is my HTML tag for getting image file:
<input type="file" name="imgFile" accept="image/*" id="imgFile" src=""/>
Here is my php code to retrieve it:
if(isset($_FILES['imgFile']))
{
$img = $_FILES['imgFile']['name'];
echo $img";
}
else
{
echo "Image not set";
}
It always generate "Image not set" as an output though I have selected an image.
Are you using the correct enctype on the form?
<form enctype="multipart/form-data">
This is required when using a file upload element.
just use:
enctype="multipart/form-data"
Say this is your form:
<form action="same_page.php" method="post" enctype="multipart/form-data">
<input type="file" name="imgFile" accept="image/*" id="imgFile" src=""/>
<input type="submit" name="upload" value="Upload" />
</form>
and your php code to retrive name of the image is in the same page where the form is, then your code should be like this:
<?php
if (isset($_POST["upload"])) {
if (isset($_FILES['imgFile'])) {
$img = $_FILES['imgFile']['name'];
echo $img;
} else {
echo "Image not set";
}
}
?>
But if your php code is in another page, then you only need to use enctype="multipart/form-data" in the form as mentioned in the other answers.
I'm trying to post form data through ajax
form1.php
I use request to get all URL parameter data
$_REQUEST["Ename"];
$_REQUEST["eImg"];
To upload the image,i use this code http://www.9lessons.info/2011/08/ajax-image-upload-without-refreshing.html
In the above link,you can see the source code,in the place of $_FILES['photoimg']['name'];,i use $_FILES['image']['name']; but it is not uploading the file and giving success message.
include('db.php');
session_start();
$session_id='1'; // User session id
$path = "uploads/";
I removed script that is marked with **
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
**if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{**
$name = $_FILES['image']['name'];
$size = $_FILES['image']['size'];
if(strlen($name)) {
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats)) {
if($size<(1024*1024)) { // Image size max 1 Mb
$actual_image_name = time().$session_id.".".$ext;
$tmp = $_FILES['image']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name)) {
mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
} else {
echo "failed";
}
} else {
echo "Image file size max 1 MB";
}
} else {
echo "Invalid file format..";
}
} **else {
echo "Please select image..!";
exit();
}**
you simply can't upload files via $.ajax().
you'll have to use some trycky iframe-stuff or something like that to make this work. luckily, there are ready-to-go plugins for jquery to handle this for you (like $.ajaxForm() for example wich seems to be the one that's used in the tutorial you're reading).
EDIT:
the plugin also allows to add extra data thats not present in the form itself. to quote the documentation:
data
An object containing extra data that should be submitted along with the form.
data: { key1: 'value1', key2: 'value2' }
For upload image by ajax you should use an iframe and set its id to form target.
Please have a look at
http://www.coursesweb.net/ajax/upload-images
It is very simple code to upload image
That won't work!
Images are handled differently from the text data in Ajax so you would have to do more than just post it using the $.ajax({}) method.
You can however use the jquery.form.js plugin it works perfect http://jquery.malsup.com/form/#download there is a tutorial on how to use it
here
Any ways I have used it my self so let me elaborate for you.
The JavaScript code is here
$('.uploadForm').live('click', function(evt){
$('#feedback').html(' ');
$('#feedback').html('<img src="images/loader_image.gif" alt="Uploading...."/>');
$("#formID").ajaxForm({
target: '#feedback'
}).submit();
evt.preventDefault();
});
If your PHP code is fine this should work .....
Just post the rest of the form fields in the normal way way
This should work for you. If the PHP code is fine
For example if you had other form fields like firstname and lastname in form like this one
<div class="form">
<fieldset class="ui-corner-all">
<h3 class="ui-widget-header ui-corner-top" align="center">Client information</h3>
<form action="save_new_client.php" enctype="multipart/form-data" id="clientForm" method="POST">
<label>First Name</label>
<input name="firstname" type="text" id="firstname" class="required" minlength="3"/>
<label>Lastname</label>
<input name="date_added" type="text" id="date_added" class="dateEst" />
<label>Image</label>
<input name="photo" type="file" id="photo" />
<input type="submit" name="button" id="button" value="Save" class="uploadForm"/>
<input type="reset" name="reset" id="button" value="Cancel" /></td>
</form>
</fieldset>
<div id="feedback"></div>
</div>
Below it you'll just need to add a div or paragraph to hold your feedback message ....
then the rest will be just fine (like I said if your PHP code is okay)I have not looked through it alot
I am trying to find example code to upload files asyncronously (via Ajax) in IE8. Also upload progress would be nice, but not mandatory. Id like PHP code to be able to deal with the file server side. I keep coming across examples for other browsers using FormData, but I cannot use that. Could any body please point me in the right direction?
This is a good tutorial on the subject: http://hungred.com/how-to/tutorial-easiest-asynchronous-upload-file-ajax-upload/
HTML:
<form id="my_form" name="form" action="upload.php" method="POST"
enctype="multipart/form-data" >
<div id="main">
<input name="my_files" id="my_file" size="27" type="file" />
<input type="button" name="action" value="Upload" onclick="redirect()"/>
<iframe id='my_iframe' name='my_iframe' src="">
</iframe>
</div>
</form>
JS:
function redirect()
{
//'my_iframe' is the name of the iframe
document.getElementById('my_form').target = 'my_iframe';
document.getElementById('my_form').submit();
}
PHP:
$uploaddir = '/images/';
$uploadfile = $uploaddir . basename($_FILES['my_files']['name']);
if (move_uploaded_file($_FILES['my_files']['my_name'], $uploadfile)) {
echo "success";
} else {
echo "error";
}
That will get you started =)
User this http://jquery.malsup.com/form/#file-upload jquery plugin..Its best and tested..
I am trying to create an avatar uploader, but I want to be able to click only one button that opens the browsing window and then automatically calls the upload method from the AvatarUpload class.
The problem I have identified is that the form doesn't seem to be posting anything.
Any help would be great!
var_dump(isset($_POST['uploaded']));
if( isset($_POST['uploaded']) )
{
$img = new AvatarUpload();
$img->startUpload();
}
else
{
?>
<form method="post" enctype="multipart/form-data" name="uploadAvatar">
<p>
<input type="file" name="uploaded" id="file" onchange="this.form.submit()" />
<p>
</form>
<?php
}
?>
when you upload files they are listed under the $_FILES, not $_POST.
I have this little form that has a button loading a little icon onto the form itself.
The button says 'browse', and there is another button says 'upload image'.
I find it kinda unnecessary to have two buttons to upload the image.
How can I make the upload happen on the end of Browse ?
here's the code by the way.
(The upload button just activate the js that calls a php file that does the trick, the js function updates it on the form)
<form class="jQ-form" action="includes/ajaxupload.php" method="post" name="standard_use" id="standard_use" enctype="multipart/form-data">
<fieldset>
<button id="image_upload_button" style="float:left;" onclick= "$('#upload_area').css('display','none');
$('#upload_area').fadeIn('slow');ajaxUpload(this.form,'includes/ajaxupload.php?filename=filename&maxSize=200000&
... more func data.'); return false;" disabled>upload icon</button>
<input type="file" id="upload_file" name="filename" style="float:left;width:70%;" size="42"/>
<p style="float:right;color:#a2983c;margin:10px;width:373px;">
Pick a nice icon that is max 300x300 pixels please
</p>
<?php
echo '<div id="upload_area" style="'.((($theiconname!='') && (file_exists($thumb_path.$theiconname))) ? '' : 'display:none;').'float:left;
width:50px;height:50px;border:3px solid #000;margin-top:12px;margin-left:3px;">';
if ($theiconname){
if (file_exists($thumb_path.$theiconname))
{
echo'<img id="the_logo" src="'.$thumb_path.$theiconname.'"/>';
}
}
?>
</div>
</fieldset>
</form>
Thanks in advance!
Sure! Just detect when the file input field has been changed, then submit the parent form. I notice you're using jQuery so I'll provide an answer using that:
$("#upload_file").change( function(){
$("#standard_use").submit();
});
Alternatively, if you're submitting this via AJAX and not actually intending to submit the form, then replace $("#standard_use").submit(); with whatever function would normally fire when someone pressed your "upload image" button.