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.
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:
<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>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.
<?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);
?>
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">10 Useful code snippets for web developers
In this post I want to suggest you 10 useful code snippets for web developers based on some frequetly asked questions I received in the past months for my readers. This collection include several CSS, PHP, HTML, Ajax and jQuery snippets.
1. CSS Print FrameworkCascading Style Sheets Framework for web printing. To use this framework download the CSS file here and use this line of code into your web pages
2. CSS @font-face
<link rel="stylesheet" href="print.css" type="text/css" media="print">This snippet allows authors to specify online custom fonts to display text on their webpages without using images:
3. HTML 5 CSS Reset
@font-face {
font-family: MyFontFamily;
src: url('http://');
}Richard Clark made a few adjustments to the original CSS reset released from Eric Meyers.
4. Unit PNG FixThis snippet fixes the png 24 bit transparency with Internet Explorer
5. Tab Bar with rounded corners
This code illustrates how to implement a simple tab bar with rounded corners:
6. PHP: Use isset() instead of strlen()
This snippet uses isset() instead strlen() to verify a PHP variable (in this example $username) is set and is at least six characters long.7. PHP: Convert strings into clickable url
<?phpif (isset($username[5])) {?>
// Do something...
}This snippet is very useful to convert a string in a clickable link. I used this snippet for several tutorials;
8. jQuery: Ajax call
<? php
function convertToURL($text) {
$text = preg_replace("/([a-zA-Z]+:\/\/[a-z0-9\_\.\-]+"."[a-z]{2,6}[a-zA-Z0-9\/\*\-\_\?\&\%\=\,\+\.]+)/"," <a href=\"$1\" target=\"_blank\">$1</a>", $text);
$text = preg_replace("/[^a-z]+[^:\/\/](www\."."[^\.]+[\w][\.\/][a-zA-Z0-9\/\*\-\_\?\&\%\=\,\+\.]+)/"," <a href="\\" target="\">$1</a>", $text);
$text = preg_replace("/([\s\,\>])([a-zA-Z][a-zA-Z0-9\_\.\-]*[a-z" . "A-Z]*\@[a-zA-Z][a-zA-Z0-9\_\.\-]*[a-zA-Z]{2,6})" . "([A-Za-z0-9\!\?\@\#\$\%\^\&\*\(\)\_\-\=\+]*)" . "([\s\.\,\<])/i", "$1<a href=\"mailto:$2$3\">$2</a>$4",
$text);
return $text;
}
?>This is the most simple way to implement an Ajax call using jQuery. Change formId and inputFieldId with the ID of the form and input field you have to submit:
9. CSS Layouts CollectionsThis page contains a collection of over 300 grids and CSS layout ready to use in your projects. Take a look, it's very useful.
10. Simple versatile multilevel navigation MenuSeveral months ago I found this simple code (HTML + CSS + JavaScript for jQuery) to implement a versatile multilevel navigation menu (please send me the original source if you find it!). I think it's the simpler and faster way to do that. The result is something like this:
The only thing you have to do is to create nested lists into a main list with id="nav", in this way:
<ul id="nav">
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
<li><a href="#">Link 3</a><ul><li><a href="#">Link 3.1</a></li><li><a href="#">Link 3.2</a></li><ul>
</li>
</ul>...and use this basic CSS code (you have to modify it to customize the layout of this menu with the style of your site!
...and this is the JavaScript code for jQuery you have to copy in the tag <head> of the pages that use this menu:
#nav, #nav ul{margin:0;
padding:0;
list-style-type:none;
list-style-position:outside;
position:relative;
line-height:26px;
}
#nav a:link,
#nav a:active,
#nav a:visited{
display:block;
color:#FFF;
text-decoration:none;
background:#444;
height:26px;
line-height:26px;
padding:0 6px;
margin-right:1px;
}
#nav a:hover{
background:#0066FF;
color:#FFF;
}
#nav li{
float:left;
position:relative;
}
#nav ul {
position:absolute;
width:12em;
top:26px;
display:none;
}
#nav li ul a{
width:12em;
float:left;
}
#nav ul ul{
width:12em;
top:auto;
}
#nav li ul ul {margin:0 0 0 13em;}
#nav li:hover ul ul,
#nav li:hover ul ul ul,
#nav li:hover ul ul ul ul{display:none;}
#nav li:hover ul,
#nav li li:hover ul,
#nav li li li:hover ul,
#nav li li li li:hover ul{display:block;}
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
function showmenu(){$("#nav li").hover(function(){$(this).find('ul:first').css({visibility:"visible", display:"none"}).show();
}, function(){
$(this).find('ul:first').css({visibility:"hidden"});
});
}
$(document).ready(function(){
showmenu();
});
</script>If you have better solution, just tell me !
Ajax Triple Dropdown with States Cities Database
Ajax Dropdown Menu it's make easy for user to use interface. When you choose first dropdown menu data in second dropdown will be filter and data related in first dropdown will be show automatic
For This Example Code is PHP and Database is MySQL
Example : Stated and Cities
1. Create Dropdown Menu (state_dropdown.php)
<?
echo "<form name=sel>\n";
echo "States : <font id=states><select>\n";
echo "<option value='0'>============</option> \n" ;
echo "</select></font>\n";
echo "Cities : <font id=cities><select>\n";
echo "<option value='0'>=== none ===</option> \n" ;
echo "</select></font>\n";
?>
<script language=Javascript>
function Inint_AJAX() {
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {} //IE
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} //IE
try { return new XMLHttpRequest(); } catch(e) {} //Native Javascript
alert("XMLHttpRequest not supported");
return null;
};
function dochange(src, val) {
var req = Inint_AJAX();
req.onreadystatechange = function () {
if (req.readyState==4) {
if (req.status==200) {
document.getElementById(src).innerHTML=req.responseText; //retuen value
}
}
};
req.open("GET", "state.php?data="+src+"&val="+val); //make connection
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=iso-8859-1"); // set Header
req.send(null); //send value
}
window.onLoad=dochange('states', -1); // value in first dropdown
</script>2. Select States and Cities to Show in Dropdown (state.php)2. Select Province Ampher Tumbon to Show in Dropdown (locale.php)
Ex 2: This is Triple Ajax Dropdown Menu - Province - Ampher - Tumbon in Thailand
<? echo "<form name=sel>\n"; echo "จังหวัด : <font id=province><select>\n"; echo "<option value='0'>============</option> \n" ; echo "</select></font>\n";
echo "อำเภอ : <font id=amper><select>\n"; echo "<option value='0'>==== ไม่มี ====</option> \n" ; echo "</select></font>\n"; echo "ตำบล : <font id=tumbon><select>\n"; echo "<option value='0'>==== ไม่มี ====</option> \n" ; echo "</select></font>\n"; ?>
<script language=Javascript>
function Inint_AJAX() {
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {} //IE
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} //IE
try { return new XMLHttpRequest(); } catch(e) {} //Native Javascript
alert("XMLHttpRequest not supported");
return null;
};
function dochange(src, val) {
var req = Inint_AJAX();
req.onreadystatechange = function () {
if (req.readyState==4) {
if (req.status==200) {
document.getElementById(src).innerHTML=req.responseText; //รับค่ากลับมา
}
}
};
req.open("GET", "locale.php?data="+src+"&val="+val); //สร้าง connection
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=tis-620"); // set Header
req.send(null); //ส่งค่า
}
window.onLoad=dochange('province', -1);
</script>2. Select Province Ampher Tumbon to Show in Dropdown (locale.php)
<?
//IE page cache
header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header ("Cache-Control: no-cache, must-revalidate");
header ("Pragma: no-cache");
header("content-type: application/x-javascript; charset=tis-620");
$data=$_GET['data'];
$val=$_GET['val'];
//ค่ากำหนดของ ฐานข้อมูล
$dbhost = "localhost";
$dbuser = "";
$dbpass = "";
$dbname = "test";
mysql_pconnect($dbhost,$dbuser,$dbpass) or die ("Unable to connect to MySQL server");
if ($data=='province') {
echo "<select name='province' onChange=\"dochange('amper', this.value)\">\n";
echo "<option value='0'>==== เลือก สังกัด ====</option>\n";
$result=mysql_db_query($dbname,"select loc_code,loc_abbr from location where loc_name = location_name and loc_code != '000000' and flag_disaster is null order by loc_abbr");
while(list($id, $name)=mysql_fetch_array($result)){
echo "<option value=\"$id\" >$name</option> \n" ;
}
} else if ($data=='amper') {
echo "<select name='amper' onChange=\"dochange('tumbon', this.value)\">\n";
echo "<option value='0'>======== เลือก ========</option>\n";
$val2=$val;
$val = substr($val,0,2);
$result=mysql_db_query($dbname,"SELECT loc_code, loc_abbr FROM location WHERE loc_code != '000000' and loc_code != '$val2' AND loc_code LIKE '$val%' AND flag_disaster IS NULL ORDER BY loc_code, loc_abbr ");
while(list($id, $name)=mysql_fetch_array($result)){
echo "<option value=\"$id\" >$name</option> \n" ;
}
} else if ($data=='tumbon') {
echo "<select name='tumbon' >\n";
echo "<option value='0'>======== เลือก ========</option>\n";
$val2=$val;
$val = substr($val,0,4);
$result=mysql_db_query($dbname,"SELECT loc_code, loc_abbr, loc_name, location_name FROM location WHERE loc_code != '000000' and loc_code != '$val2' AND loc_code LIKE '$val%' AND flag_disaster IS NULL ORDER BY loc_code, loc_abbr");
while(list($id, $name)=mysql_fetch_array($result)){
echo "<option value=\"$id\" >$name</option> \n" ;
}
}
echo "</select>\n";
?>(MySQL)
PS. In ajax-dropdown.rar file Include
for states and cities (america)
state.php
state_dropdown.php
state.sql (MySQL)
for province ampher tumon (thailand)
locale.php
locale_dropdown.php
location.sql
If you have better solution, just tell me !PHP for Microsoft Ajax Library
The Microsoft AJAX Library is a pure-JavaScript library that's used by ASP.NET AJAX but is also available as a separate download. Because it's pure JavaScript, it's not tied to ASP.NET on the backend. PHP for MS AJAX is code to help you make use of the Microsoft AJAX Library from PHP applications. With this first Alpha release, it simply supports exposing PHP classes as AJAX-enabled web services, just as in ASP.NET applications. In fact, the generated proxies are identical to what you get from ASP.NET, meaning you can have full interoperability.
Hello World
The service on the backend so to speak:
HTML:
<?php require_once '../../dist/MSAjaxService.php'; class HelloService extends MSAjaxService { function SayHello($name) { return "Hello, " . $name . "!"; } } $h = new HelloService(); $h->ProcessRequest();And the front end that will talk to it:
<title>Hello, World!</title> <script type="text/javascript" src="../../MicrosoftAjaxLibrary/MicrosoftAjax.js"></script> <script type="text/javascript" src="HelloService.php/js"></script> </head> Name: <input id="name" type="text" /> <input type="button" value="Say Hello" onclick="button_click(); return false;" /> <br /> Response from server: <span id="response"></span> </body> <script type="text/javascript"> function button_click() { HelloService.SayHello($get('name').value, function (result) { $get('response').innerHTML = result; }); } </script> </html>If you have better solution, just tell me !
FirePHP: Tying together Firebug and PHP
FirePHP solves the problem of AJAX debugging by sending debug information along with the response. To avoid breaking the response content, the debug information is placed into special HTTP response headers.
This works for all types of requests, not just AJAX requests, which means you can even debug requests for images that are dynamically generated by a PHP script. You can use FirePHP in your development environment, or use it to track down bugs that only appear on your production site.This is what Christoph Dorn has to say about FirePHP in his recent writeup.He goes into detail on how you can setup the Firebug plugin, and how you use it from within PHP:
// use an ini file to turn it on and off if ($settings['FirePHP'] == 'Enabled') { FB::setEnabled(true); } else { FB::setEnabled(false); } // log away! // selectively log if (Debug::getOption('DisableCache')) { // code to disable cache FB::info('Cache has been disabled!'); } else { // default code }Check out the article for more info.
In related news, Zend just stepped it up a notch with their new Zend Server that fits in nicely with the cloud
If you have better solution, just tell me !
Showing progress with the Safari 4 multiple file upload
Andrea Giammarchi has taken the new Safari 4 implementation of multi input file upload functionality and has written an article on how to write the client and server to enable this.He shares the new XHR implementation:
var xhr = new XMLHttpRequest, upload = xhr.upload; upload.onload = function(){ console.log("Data fully sent"); }; xhr.open("post", page, true); xhr.send(binaryData);and the delves into a PHP server backend that groks things like X-File-Size and X-File-Name.
Then, he shows the client side code to push this all forward and packages it all up:
If you have better solution, just tell me !
Using Base64 encoded images on IE too
Being able to use data: URIs to do interesting things such as inline images is incredibly useful.
IE 8 added support for data URIs but what about older versions of IE (which are still far too prevalent)?
This nice PHP script shows how you can send back data URIs for those who support it, and for older IE, use the message/rfc822 mime type that email clients often use to encode images:
header('Content-type:message/rfc822'); MIME-Version: 1.0 Content-Type: multipart/related; boundary="NEXT_MHTML_DATA_PART" --NEXT_MHTML_DATA_PART Content-Location: Content-Transfer-Encoding: quoted-printable Content-Type: text/html; charset="utf-8" <!-- put the HTML in here including a for loop displaying: --> <div class="img" style="background-image:url(MHTML_IMG<?php echo $index?>)"></div> --NEXT_MHTML_DATA_PART Content-Transfer-Encoding: base64 Content-Type: image/png <!-- the image data here --> --NEXT_MHTML_DATA_PART Content-Location: END_OF_MHTML_FILE Content-Transfer-Encoding: base64 Content-Type: image/png IE_NEED_THIS_TO_END_DATAIf you have better solution, just tell me!
Time and Date difference using a PHP function
This is a simple PHP function dateTimeDiff() written for an application that I am developing, useful to get time and date difference between two date (a reference date and "now"), with a Digg-like style (ex: 12 min 20 sec ago). The mask of reference for each date is 2007-10-18 20:05:22, a standard MySQL datetime field.
Download Sample Code
How it works?
First, you have to include the file time Function.php into the PHP file that will use the function.
<?php include('timeFunction.php') ?>... and you have to pass the data which it goes made the comparison:
dateTimeDiff($dataRef);... where $dataRef is, for example, a value from a SQL query.
The codeThis is the code of dateTimeDiff() PHP function:If you have better solution, just tell me !
<?php function dateTimeDiff($data_ref){
// Get the current date
$current_date = date('Y-m-d H:i:s');
// Extract from $current_date
$current_year = substr($current_date,0,4);
$current_month = substr($current_date,5,2);
$current_day = substr($current_date,8,2);
// Extract from $data_ref
$ref_year = substr($data_ref,0,4);
$ref_month = substr($data_ref,5,2);
$ref_day = substr($data_ref,8,2);
// create a string yyyymmdd 20071021
$tempMaxDate = $current_year . $current_month . $current_day;
$tempDataRef = $ref_year . $ref_month . $ref_day;
$tempDifference = $tempMaxDate-$tempDataRef;
// If the difference is GT 10 days show the date
if($tempDifference >= 10){
echo $data_ref;
} else {
// Extract $current_date H:m:ss
$current_hour = substr($current_date,11,2);
$current_min = substr($current_date,14,2);
$current_seconds = substr($current_date,17,2);
// Extract $data_ref Date H:m:ss
$ref_hour = substr($data_ref,11,2);
$ref_min = substr($data_ref,14,2);
$ref_seconds = substr($data_ref,17,2);
$hDf = $current_hour-$ref_hour;
$mDf = $current_min-$ref_min;
$sDf = $current_seconds-$ref_seconds;
// Show time difference ex: 2 min 54 sec ago.
if($dDf<1){
if($hDf>0){
if($mDf<0){
$mDf = 60 + $mDf;
$hDf = $hDf - 1;
echo $mDf . ' min ago';
} else {
echo $hDf. ' hr ' . $mDf . ' min ago';
}
} else {
if($mDf>0){
echo $mDf . ' min ' . $sDf . ' sec ago';
} else {
echo $sDf . ' sec ago';
}
}
} else {
echo $dDf . ' days ago';
}
?>






