it is not possible to process a file upload through the XMLHttpRequest object, becouse JavaScript has no access to your computer's file system. But, there are still ways to perform Ajax-like functionality for this task without making use of the XMLHttpRequest object.
This can be done via a hidden <iframe>, using the following method, which has four main steps:

  1. Creates a form (with a file element) and a hidden iframe. The iframe must have a name (name attribute). The <form> tag must have added a "target" attribute whose value is the name of <iframe> and an onsubmit() event (with return false;) that sends form data to a JavaScript function for the page is not refreshed when you press the Submit button.
  2. The JavaScript function uses the submit() event to sends form data to the iframe (where the target attribute indicates). The iframe transmits these data to a PHP script whose address is added in its "src" attribute.
  3. The PHP script uploads the image file on the server, and returns (in the same Iframe) a BODY tag with an "onload" attribute, which calls another JavaScript function in the main page (parent), transferring as a parameter the address of the file that was just copied to the server.
  4. This second JS function is used to display the image uploaded. It takes the address of the file loaded on the server and adds in a DIV (with "innerHTML") an <img> tag with the image uploaded.

Between the first step, sending the file and display it in the 4 step, it takes some time. Becouse the user does not know what happens with uploading, especially if the file is large, you can use the innerHTML property to display a loading message to the user while the PHP script is performing its functionality.

This is briefly the theoretical part, study the example below, where are applied the steps outlined above.
The example contains 3 files: Below are the codes for each file. You must create them in the same directory. Explanations about the role of each function are found in the code documentation.
If you wish to use this model in your sites, you must create a folder where to be copied the images (named "imgs" and CHMOD permissions 0777). Or you can download the script from here -> Upload images.

The code for "index.php"

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Ajax Upload - Show Image</title>
<style type="text/css">
 #uploadframe { display:none; }
</style>
<script type="text/javascript" src="functions.js"></script>
</head>
<body>

<div id="showimg"> </div>
<form id="uploadform" action="upload_img.php" method="post" enctype="multipart/form-data" target="uploadframe" onsubmit="uploadimg(this); return false">
 <input type="file" id="myfile" name="myfile" />
 <input type="submit" value="Submit" />
 <iframe id="uploadframe" name="uploadframe" src="upload_img.php" width="8" height="8" scrolling="no" frameborder="0"></iframe>
</form>

</body>
</html>
 

The code for "functions.js"

/*** Script from https://coursesweb.net/ajax/ ***/

// gets data from the form and sumbit it
function uploadimg(theform){
 theform.submit();

 // calls the function to display Status loading
 setStatus("Loading...", "showimg");
 return false;
}

// this function is called from the iframe when the php return the result
function doneloading(rezultat) {
 // decode (urldecode) the parameter wich is encoded in PHP with 'urlencode'
 rezultat = decodeURIComponent(rezultat.replace(/\+/g, " "));

 // add the value of the parameter inside tag with 'id=showimg'
 document.getElementById('showimg').innerHTML = rezultat;
}

// displays status loading
function setStatus(theStatus, theloc) {
 var tag = document.getElementById(theloc);

 // if there is "tag"
 if (tag) {
 // adds 'theStatus' inside it
 tag.innerHTML = '<b>'+ theStatus + "</b>";
 }
}
 

Code for "upload_img.php"

<?php
// Script from https://coursesweb.net/ajax/

$savefolder = 'imgs'; // folder for upload
$max_size = 250; // maxim size for image file, in KiloBytes

// Allowed image types
$allowtype = array('bmp', 'gif', 'jpg', 'jpeg', 'gif', 'png');

/** Uploading the image **/

$rezultat = '';
// if is received a valid file
if (isset ($_FILES['myfile'])) {
 // checks to have the allowed extension
 $type = end(explode(".", strtolower($_FILES['myfile']['name'])));
 if (in_array($type, $allowtype)) {
 // check its size
 if ($_FILES['myfile']['size']<=$max_size*1000) {
 // if no errors
 if ($_FILES['myfile']['error'] == 0) {
 $thefile = $savefolder . "/" . $_FILES['myfile']['name'];
 // if the file can`t be uploaded, return a message
 if (!move_uploaded_file ($_FILES['myfile']['tmp_name'], $thefile)) {
 $rezultat = 'The file can`t be uploaded, try again';
 }
 else {
 // Return the img tag with uploaded image.
 $rezultat = '<img src="'.$thefile.'" />';
 echo 'The image was successfully loaded';
 }
 }
 }
 else { $rezultat = 'The file <b>'. $_FILES['myfile']['name']. '</b> exceeds the maximum permitted size <i>'. $max_size. 'KB</i>'; }
 }
 else { $rezultat = 'The file <b>'. $_FILES['myfile']['name']. '</b> has not an allowed extension'; }
}

// encode with 'urlencode()' the $rezultat and return it in 'onload', inside a BODY tag
$rezultat = urlencode($rezultat);
echo '<body onload="parent.doneloading(\''.$rezultat.'\')"></body>';
?>

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which HTML5 tag is indicated to be used as container for menu with navigation links in Web site?
<section> <nav> <article>
<nav><ul>
 <li><a href="http://coursesweb.net/css/" title="CSS Course">CSS Course</a></li>
 <li><a href="http://www.marplo.net/jocuri/" title="Flash Games">Flash Games</a></li>
</ul></nav>
Which CSS property shifts an item horizontally to the left or right of where it was?
text-align clear float
.some_class {
  width: 30%;
  float: left;
}
Click on the Math object method which returns x, rounded downwards to the nearest integer.
Math.ceil(x) Math.abs(x) Math.floor(x)
var num = 12.34567;
num = Math.floor(num);
alert(num);       // 12
Indicate the PHP function which returns the number of characters in string.
mb_strlen() count() stristr()
$str = "string with utf-8 chars åèö";
$nrchr = mb_strlen($str);
echo $nrchr;        // 30
Uploading images to server with Ajax

Last accessed pages

  1. Send Email with Nodemailer (520)
  2. Read Excel file data in PHP - PhpExcelReader (56583)
  3. PHP PDO - exec (INSERT, UPDATE, DELETE) MySQL (41515)
  4. Add, Change, and Remove Attributes with jQuery (35983)
  5. Register and show online users and visitors (22711)

Popular pages this month

  1. Read Excel file data in PHP - PhpExcelReader (320)
  2. PhpSpreadsheet - Read, Write Excel and LibreOffice Calc files (265)
  3. Register and show online users and visitors (253)
  4. Courses Web: PHP-MySQL JavaScript Ajax HTML CSS Flash-AS3 (244)
  5. Insert, Select and Update NULL value in MySQL (156)