I am writing my first Ajax-PHP script. I have succeded to call the php file from the javascript file and then get an echo from the php file. But I also want to upload the file and I don´t know how to complete the code so it also uploads the file to server without reloading the page.
When the file has been uploaded I want the filename to be printet in the div tag called “uploadedFiles” in te upload.html file.
Please, help!
upload.html
[code]
<html>
<head>
<body>
<form id=”uploadForm” name=”uploadForm” enctype=”multipart/form-data” method=”post” onsubmit=”uploadFile();” action=””>
<label>
<input type=”file” name=”upload_file” />
<br />
<br />
<input type=”submit” name=”upload” id=”upload” value=”Upload” />
</label>
</form>
<div id=”uploadedFiles” align=”left”><p id=”val”></p></div>
<html>
<head>
<body>
upload.js
[code]function uploadFile()
{
var xmlHttp;
try
{
xmlHttp = new XMLHttpRequest();
}
// For older versions than IE6
catch(e)
{
var XmlHttpVersions = new Array(“MSXML2.XMLHTTP.6.0”,
“MSXML2.XMLHTTP.5.0”,
“MSXML2.XMLHTTP.4.0”,
“MSXML2.XMLHTTP.3.0”,
“MSXML2.XMLHTTP”,
“Microsoft.XMLHTTP”);
for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++)
{
try
{
xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
}
catch (e)
{
alert(“Something went wrong”);
}
}
}
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4)
{
document.uploadForm.test.value = xmlHttp.responseText;
}
}
xmlHttp.open(“GET”, “upload.php”, true);
xmlHttp.send(null);
}
upload.php
[code=php]<?php
$maxsize = 28480;
if( !$_POST[‘upload’] )
$error = “Error: Try again.”;
if(!is_uploaded_file($_FILES[‘upload_file’][‘tmp_name’]) and !isset($error))
{
$error = “A file has to be uploaded.”;
}
if($_FILES[‘upload_file’][‘size’] > $maxsize and !isset($error))
{
$error = “Maximum 20 kB”;
}
if($_FILES[‘upload_file’][‘type’] != “image/gif” and
$_FILES[‘upload_file’][‘type’] != “image/pjpeg” and
$_FILES[‘upload_file’][‘type’] != “image/jpeg”)
{
$error = “It mus be a gif or jpeg file.”;
}
if(!isset($error))
{
$filename = $_FILES[‘upload_file’][‘name’];
move_uploaded_file($_FILES[‘upload_file’][‘tmp_name’], “filer/$filename”);
echo “Thanks for uploading!”;
exit;
}
else
{
echo $error;
}
?>