I am trying to upload an image file using ajax to the server. However, till now i have only transported data to the background php script using ajax. I haven’t done so with files.However, I am trying as follows:-
<form id="imageUploadForm" action="profileThis.php" method="POST"
enctype="multipart/formdata">
<input type="file" id="boozeImgFile" name="boozeImgFile" >
<input type="button" onclick="uploadImage()" value="Upload">
</form>
And my ajax code is as follows
$("imageUploadForm").request(
{
method:'post',
parameters:{category:$("category").value, categoryId:$("categoryId").value, userId:
$("userInSession").value, uploadImage:'true'},
onComplete:function()
{
alert("successfully uploaded to profilethis.php");
},
onSuccess:function(ajax)
{
alert(ajax.responseText);
},
onFailure:ajaxFailure,
onException:ajaxFailure
});
However, when I am trying to retrieve it in my background script using $filename=$_FILES["boozeImgFile"]["name"] its not working
My profileThis.php looks like this
if(isset($_REQUEST['uploadImage']))
{
$name=$_FILES["boozeImgFile"]["name"];
$tempName=$_FILES["boozeImgFile"]["tmp_name"];
$size=$_FILES["boozeImgFile"]["size"];
$type=$_FILES["boozeImgFile"]["type"];
if(($type=="image/jpg"||$type=="image/jpeg"||$type=="image/pjpeg")&& ($size>0&&$size<=4096000))
{
$userId=clearSpecialChars($_REQUEST['userId']);
$tempName=$_FILES["boozeImgFile"]["tmp_name"];
$category=clearSpecialChars($_REQUEST['category']);
$categoryId=clearSpecialChars($_REQUEST['categoryId']);
$name="img_".$userId."_".$filename;
$rootDir="C:/xampp/htdocs";
$dir="/boozeimg/".$category."/".$categoryId;
$fullDirectory=$rootDir.$dir;
$realPath=$dir."/".$name;
$fullPath=$rootDir.$dir."/".$name;
if(is_dir($fullDirectory))
{
move_uploaded_file($tempName, $fullPath);
}
else
{
mkdir($fullDirectory,0777,true);
move_uploaded_file($tempName, $fullPath);
}
}
In profileThis.php the first line inside the if condition doesn’t reach, however the if condition by itself does reach
Well the quick answer is you can’t. You can’t use AJAX to upload files. What you can do is have the target of a form be a hidden iframe and submit your form to that. It is essentially the same thing in result, but technically completely different. Most people still use the term ajax (including my forthcoming url), but it’s definitely not ajax. Here’s a link with a short tutorial:
http://www.coursesweb.net/ajax/upload-images