Techs Worldwide has moved to a new location with a new name and more advanced features. Click here to visit Geeks Worldwide for technology news, tutorials, videos, tools, and discussions.
Today: 07/04/2009
 

AJAX File Uploads (using Dojo and PHP)

It is easy to upload files using Ajax and PHP. How? I'll try to explain below.

We'll be using some common sense, Dojo Framework for AJAX, HTML, Apache, Javascript, and PHP. Make sure you install Apache and PHP (read other tutorials for that). I'll explain how to setup Dojo (for this tutorial) below.

Make sure you configure PHP to allow file uploads.

Fire up your browser and go to http://dojotoolkit.org/. Download Dojo form the website. I've used version 0.4.1 for this tutorial.

  • After downloading the zip file go to the folder where you want to put your file upload code (I've named this file index.php). Unzip the downloaded file in that folder and rename the new folder created (e.g. dojo-0.4.1-ajax.zip) to 'dojo' (w/o quotes).
  • Enter the code below in the head (between <head> and </head>) section of your HTML file that contains file upload form. I'm naming it index.php.

    <script language="javascript" type="text/javascript" src="./dojo/dojo.js"></script>

  • Now in the body of index.php enter HTML code below.
    <form id="upload_file" action="file_upload_script.php" 
          method="post" enctype="multipart/form-data">
    <input type="hidden" name="MAX_FILE_SIZE" value="8388608" />
    <input type="file" name="select_file" tabindex="1" size="35" />
    <input type="button" value="Submit" 
           onClick="upload_file_submit()" 
           tabindex="2">
    </form>
    

    For the sake of simplicity, I am using a very simple form. You can add more fields if you want.

  • Now, enter the javascript code below in the head section of index.php.

    <script language="javascript">
    <!--
    // Dojo configuration and Variable Initialization
    // Put this code in index.php before the line where you include the javascript for dojo
    // djConfig = { isDebug: true };
    dojo.require("dojo.io.*");
    dojo.require("dojo.io.IframeIO");
    ctr = 0;
    function upload_file_submit()
    {
    var bindArgs = {
    formNode: document.getElementById("upload_file"), //form's id
    mimetype: "text/plain", //Enter file type info here
    content:
    {
    increment: ctr++,
    name: "select_file", //file name in the form
    post_field: "" // add more fields here .. field will be accessible by $_POST["post_field"]
    },
    handler: function(type, data, evt)
    {
    //handle successful response here
    if(type == "error") alert("Error occurred.");
    else
    {
    //getting error message from PHP's file upload script
    res = dojo.byId("dojoIoIframe").contentWindow.document.getElementById("output").innerHTML;
    //Incase of an error, display the error message
    if(res != "true") alert(res);
    else alert("File uploaded successfully.");
    }
    }
    };
    var request = dojo.io.bind(bindArgs);
    }
    //-->
    </script>

  • Now, create a file named file_upload_script.php and put the code below in that file. Please note that this is the script that is mentioned in "action" attribute of the form tag above.

    <script language="php">
    // You can send any message to javascript client using die(create_message(<message>)); ...
    //this function will terminate the script and will return control to the client
    if( isset($_POST["MAX_FILE_SIZE"]) && isset($_FILES))
    {
    if( $_FILES['select_file']['size'] > $_POST["MAX_FILE_SIZE"])
    die(create_message("File size must be less than ".$_POST["MAX_FILE_SIZE"]." bytes."));
    $uploadFile = "./file_name_on_server.txt";

    if(move_uploaded_file( $_FILES['select_file']['tmp_name'], $uploadFile))
    {
    $fp = fopen($uploadFile, "rb");
    if(!$fp) die(create_message("Error opening uploaded file."));
    fclose($fp);
    // SENDING TRUE IS MANDATORY SO THAT THE JAVASCRIPT
    //FUNCTION KNOWS THAT THE FILE HAS BEEN UPLOADED PROPERLY
    die(create_message("true"));
    }
    else die(create_message( $_FILES['select_file']['tmp_name']." could not be uploaded successfully."));
    }
    else die(create_message( "Error in form input: Data is missing. "));

    function create_message($string)
    {
    $output = "";
    $output .= "<html><head></head><body>";
    $output .= "<textarea id=\"output\">";
    $output .= trim($string);
    $output .= "</textarea>";
    $output .= "</body></html>";
    return $output;
    }
    </script>

    That's it. Go to index.php from your browser and upload a text file. Press submit. If there is no error you should see the "File uploaded successfully" message.

=======================================================================================

Support Geeks Worldwide:

Link to us:

You can support us by putting a link to our website on your blog or website (code is below).

<a href="http://www.techsww.com/">
Geeks Worldwide - Tutorials about Software Installation,
Configuration, Administration, Monitoring, Tools, Tips &
Tricks
</a>

OR a simple one.

<a href="http://www.techsww.com/">
Geeks Worldwide - IT related Tutorials
</a>

Feedbacks:

We appreciate feedbacks and suggestions about our tutorials and Geeks Worldwide from readers. Please contact us using the form here and let us know what you think about the tutorial and the website in general.

Bookmark Us:

We are working on new features for the website, please keep visiting or bookmark us using your favourite bookmarking service.

Subscribe to RSS:

You can subscribe to our RSS feed here.



 
Creative Commons License   Valid XHTML 1.0 Transitional Valid CSS