PHP script example, Ajax upload

While the upload via XMLHttpRequest is not possible are there many examples and tutorials to upload file via some "virtual IFRAME".
In this quick tutorial we will show how-to create such an Ajax upload form using the jQuery Form plug-in and our easy upload class.The system is very simple, build your upload form just like normal. In place of posting the form to the script you use some JavaScript code to post the data to some PHP script in the background.


<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript">

$(document).ready(function() {
$("#loading")
.ajaxStart(function(){
$(this).show();
})
.ajaxComplete(function(){
$(this).hide();
});
var options = {
beforeSubmit: showRequest,
success: showResponse,
url: 'upload4jquery.php', // your upload script
dataType: 'json'
};
$('#Form1').submit(function() {
document.getElementById('message').innerHTML = '';
$(this).ajaxSubmit(options);
return false;
});
});

function showRequest(formData, jqForm, options) {
var fileToUploadValue = $('input[@name=fileToUpload]').fieldValue();
if (!fileToUploadValue[0]) {
document.getElementById('message').innerHTML = 'Please select a file.';
return false;
}

return true;
}

function showResponse(data, statusText) {
if (statusText == 'success') {
if (data.img != '') {
document.getElementById('result').innerHTML = '<img src="/upload/thumb/'+data.img+'" />';
document.getElementById('message').innerHTML = data.error;
} else {
document.getElementById('message').innerHTML = data.error;
}
} else {
document.getElementById('message').innerHTML = 'Unknown error!';
}
}

</script>

Next create a PHP script named "upload4jquery.php" and place it in the same directory where other files are located. Place this code into that new file:


<?php
include($_SERVER['DOCUMENT_ROOT'].'/classes/upload/foto_upload_script.php');

$foto_upload = new Foto_upload;

$json['size'] = $_POST['MAX_FILE_SIZE'];
$json['img'] = '';

$foto_upload->upload_dir = $_SERVER['DOCUMENT_ROOT']."/upload/";
$foto_upload->foto_folder = $_SERVER['DOCUMENT_ROOT']."/upload/";
$foto_upload->thumb_folder = $_SERVER['DOCUMENT_ROOT']."/upload/thumb/";
$foto_upload->extensions = array(".jpg", ".gif", ".png");
$foto_upload->language = "en";
$foto_upload->x_max_size = 480;
$foto_upload->y_max_size = 360;
$foto_upload->x_max_thumb_size = 120;
$foto_upload->y_max_thumb_size = 120;

$foto_upload->the_temp_file = $_FILES['fileToUpload']['tmp_name'];
$foto_upload->the_file = $_FILES['fileToUpload']['name'];
$foto_upload->http_error = $_FILES['fileToUpload']['error'];
$foto_upload->rename_file = true;

if ($foto_upload->upload()) {
$foto_upload->process_image(false, true, true, 80);
$json['img'] = $foto_upload->file_copy;
}

$json['error'] = strip_tags($foto_upload->show_error_string());
echo json_encode($json);
?>
This tutorial or guide is not about how to use the easy upload class. If you never used the class before try the example files first and than start with this Ajax upload form.

Paths and upload directories

You need to create some upload directories (2 one for the upload and one for the thumbs) and check the permission (chmod the upload directory with 777). If you use the same structure as suggested in the class file you don't need to change the include at the top from the PHP script.

Now we need the form HTML and some other containers where the response data is placed.

<form id="Form1" name="Form1" method="post" action="">
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_size; ?>" />
Select an image from your hard disk:

<div>
<input type="file" name="fileToUpload" id="fileToUpload" size="18" />
<input type="Submit" value="Submit" id="buttonForm" />
</div>
</form>
<img id="loading" src="loading.gif" style="display:none;" />

<p id="message">

<p id="result">

jquery ajax error handling

How to handle ajax errors using jQuery ?

jQuery is the most awesome javascript library that made easy for asynchronous ajax calls.it has global ajax function and some pre defined ajax functions like $.get, $.post, load .etc. but we don’t find any error messages by default with this library. we can see the errors with firefox’s addon firebug or with IE developer toolbar.So we manage most common ajax errors in our application with global ajaxSetup function which come with jQuery by default. We can set many options,to see available ajaxsetup options.

most ajax errors we get errors are server response errors and some JSON parse errors. To know more about the HTTP errors details please check here. To test this error handling just copy and paste it to your head section of HTML document.

Javascript Code for setting global error handling.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$().ready(function(){
$.ajaxSetup({
error:function(x,e){
if(x.status==0){
alert('You are offline!!\n Please Check Your Network.');
}else if(x.status==404){
alert('Requested URL not found.');
}else if(x.status==500){
alert('Internel Server Error.');
}else if(e=='parsererror'){
alert('Error.\nParsing JSON Request failed.');
}else if(e=='timeout'){
alert('Request Time out.');
}else {
alert('Unknow Error.\n'+x.responseText);
}
}
});
});
In the above example we handle following common error and show response text for other rare errors.

  • 0-xhr status ,is it initialized or not that means user is offline.

  • 404-page not found

  • 500-Internel Server error.

  • request timeout – jQuery custom error.

  • parseerror-jQuery custom error when parsing JSON data.

  • we just throw other errors with response error