Home > PHP, Tutorials > Faking an AJAX upload script

Faking an AJAX upload script

July 14th, 2008

Ever wanted to make an upload script, but don't want the page to refresh? Try AJAX.

In this tutorial we'll use an iframe to simulate AJAX behaviour.

Firstly, we "might" want to create a simple upload form:

 
<p id="f1_upload_process">Loading...<br/><img src="loader.gif" />
<p id="result">
<form action="admin/addpost.php" method="post" enctype="multipart/form-data" target="upload_target" onsubmit="startUpload();" >
		File:
<input name="myfile" type="file" />
<input type="submit" name="submitBtn" value="Upload" />
	</form>
 
	<iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:0px solid #fff;"></iframe>
 

The important part here is the enctype, always have the enctype specified if you're uploading files. The first paragraph is the little Loading... box that'll show up when we press the submit button. The second <p> "result" is to display the results (We've uploaded or We failed). And lastly the iframe that is actually submitting the data, specified through the target="upload_target" in the form. Also, the forms onsubmit triggers the startUpload(); function.

Now we want to add some Javascript functions:

 
 
<script type="text/javascript">
function startUpload(){
document.getElementById('f1_upload_process').style.visibility = 'visible';
return true;
}
function stopUpload(success){
if (success == 1){
document.getElementById('result').innerHTML =
'
<div class="msg">The file was uploaded successfully!</div>
 
';
} else {
document.getElementById('result').innerHTML =
'
<div id="error">There was an error during file upload!</div>
 
';
}
document.getElementById('f1_upload_process').style.visibility = 'hidden';
return true;
}
</script>

The function called startUpload(); does nothing more than show the #f1_upload_process div which contains the text "Loading..." and an image. the stopUpload function, though, checks the success variable passed to it, and adjusts the text of the #result accordingly and hides the "Loading".

So far, we have an ugly form. Lets add some style to it, make it look good.

 
 
#f1_upload_process{
z-index:100;
position:absolute;
visibility:hidden;
text-align:center;
width:400px;
margin:0px;
padding:0px;
background-color:#fff;
border:1px solid #ccc;
}
 
form[target='upload_target']{
text-align:center;
width:390px;
margin:0px;
padding:5px;
background-color:#fff;
border:1px solid #ccc;
}
 

I've used a conditional parameter on the form, so all other forms can stay as they are, and I didn't have to give the form an id or class. Then, one more thing; the PHP:

 
 
<?php
if (isset($_FILES['myfile'])) :
$destination_path = "./"; // This folder (don't forget trailing /)
$result = 0; // Not succesful yet
$target_path = $destination_path . basename( $_FILES['myfile']['name']); // Target path (This folder + Filename);
if(@move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) { // move the file
$result = 1; // success!
}
sleep(1);
// Echo the javascript to call the stopUpload function.
?>
<script language="javascript" type="text/javascript">
window.top.window.stopUpload(&lt;?php echo $result; ?>);
</script>
<?php
die(); // Dont forget this, if not you'll echo the form again.
endif;
?>
 

Now save it as a PHP file and run it on your webserver, voila.

Click to download source

Popularity: 27% [?]

PHP, Tutorials

  1. July 17th, 2008 at 18:55 | #1

    Simple and effective. This is what I was looking for. Works perfect. I’ll plug this into my current file upload class and it should work great.

  2. July 18th, 2008 at 16:17 | #2

    Wow, thanks for the reply. It’s good to know people are actually doing something with my posts.
    Thanks for the thumbs up!

  3. Dejan
    July 31st, 2008 at 01:20 | #3

    Excellent. Simple and efficient. Thank you.

  4. Ilias
    August 15th, 2008 at 16:19 | #4

    window.top.window.stopUpload(<?php echo $result; ?>);
    ^- There’s a little mistake on that line, it shouldn’t say “<” but “<”.

    Also; there’s a shorthand for this:
    window.top.window.stopUpload();

  5. Ilias
    August 15th, 2008 at 16:20 | #5

    Oh, you fucking scripts are screwing this up :p

    let’s try again:

    it says “&lt;” instead of “<”

    furthermore you can use “<?=” instead of “<?php echo”.

  6. August 17th, 2008 at 21:36 | #6

    Ok, let’s try this one more time..
    *breathes out slowly*

    First of all, it says “&lt;” (which is the html-entity for) “<”
    so
    window.top.window.stopUpload(&lt;?php echo $result; ?>);
    should be
    window.top.window.stopUpload(<?php echo $result; ?>);</code

    Secondly; not a mistake, but something that might be useful to know, is that there is a shorthand for writing
    <? echo $boe; ?>
    it goes like this:
    <?= $boe; ?gt;

  7. August 17th, 2008 at 21:36 | #7

    Goddamnit, last “?gt” should read “?>”

  8. September 7th, 2008 at 20:47 | #8

    Actually Ilias, <?= is deprecated.

  9. Michael
    July 3rd, 2011 at 02:37 | #9

    Any chance you’re still alive and remember this post?

    Isn’t this:
    <form action="
    reloading the page? The script is calling itself after the onsubmit is completed, isn’t it?

  1. August 28th, 2008 at 04:31 | #1