Saturday, 5 May 2012

AJAX FILE UPLOAD

The examples below cannot be used with file uploads inside a form. To submit form with file uploads, see the example Submitting HTML Forms With AJAX.
To upload a file asynchronously, we need a cgi script. You have to move upload.cgi found in your download, to a directory where cgi scripts are allowed. For example; in most servers, there is a "cgi-bin" folder to do it. Note that it must be executable. If you work in your local, you need "PERL" installed. Please, read the instructions in the readme.txt file for that.
After that, you just need to call PLX.AjaxifyUpload method for the file inputs. You can control the upload with some parameters. Show parameters here:
Let's start with a basic example:
Example #1:
  1. <?  
  2. function upload($tmp_name$name){  
  3.     // do not forget to control file type and size  
  4.     move_uploaded_file($tmp_name"uploads/" . $name);  
  5. }  
  6. include("PHPLiveX.php");  
  7. $ajax = new PHPLiveX("upload");  
  8. ?>  

  1. <? $ajax->Run(); ?>  
  2. <div style="float:left;"><input type="file" id="photo" name="photo"></div>  
  3. <div id="percent" style="float:left;">% 0</div>  

  1. <script type="text/javascript">  
  2. PLX.AjaxifyUpload("photo", {  
  3.     tmp_dir: "tmp",  
  4.     cgi_path: "cgi-bin/upload.cgi",  
  5.     onProgress: function(progress){  
  6.         document.getElementById("percent").innerHTML = "% " + progress.percent;  
  7.         if(progress.completed)  
  8.             upload(progress.file_tmp_name, progress.file_name, {});  
  9.     }  
  10. });  
  11. </script>  
Select a file:   
% 100

* If you create more than one ajax uploads with the same options, you don't need to call AjaxifyUpload method for each. It may be used like PLX.AjaxifyUpload(["photo1", "photo2", "photo3"], {...})
PHP codes ahead are also used in following examples.
Example #2:
  1. <div  
  2.     <div style="float:left;"><input type="file" id="img1" name="img1"></div>  
  3.     <div id="per_img1" style="float:left;">% 0</div>  
  4. </div>  
  5. <div  
  6.     <div style="float:left;"><input type="file" id="img2" name="img2"></div>  
  7.     <div id="per_img2" style="float:left;">% 0</div>  
  8. </div>  

  1. <script type="text/javascript">  
  2. PLX.AjaxifyUpload(["img1""img2"], {  
  3.     tmp_dir: "tmp",  
  4.     cgi_path: "cgi-bin/upload.cgi",  
  5.     onProgress: function(progress){  
  6.         var percent = document.getElementById("per_" + progress.id);  
  7.         percent.innerHTML = "% " + progress.percent;  
  8.         if(progress.completed){  
  9.             upload(progress.file_tmp_name, progress.file_name, {  
  10.                 onFinish: function(response){  
  11.                     percent.innerHTML = "Yükleme işlemi başarıyla tamamlandı!";  
  12.                 }  
  13.             });  
  14.         }  
  15.     }  
  16. });  
  17. </script>  
Upload progress is completed!
Upload progress is completed!

We have seen how simple it is. Let's add more option to the upload and increase the visuality:
  1. <div  
  2.     <div style="float:left;"><input type="file" id="homework" name="homework"></div>  
  3.     <div id="pr" style="float:left;border:1px solid #CCC;width:100px;">  
  4.         <div id="pr_bar" style="width:0px;background-color:#FF0000;position:absolute;">&nbsp;</div>  
  5.         <div id="pr_text" align="center" style="position:relative;">% 0</div>  
  6.     </div>  
  7. </div>  
  8. <div style="float:left;margin-left:15px;" align="center">  
  9.     <input type="button" value="Yükle" onclick="PLX.InitializeUpload('homework')">  
  10. </div>  

  1. <script type="text/javascript">  
  2. PLX.AjaxifyUpload("homework", {  
  3.     cgi_path: "cgi-bin/upload.cgi",  
  4.     tmp_dir: "tmp",  
  5.     allowed_types: ["txt""rtf""doc""odt""pdf""xls"],  
  6.     insensitivity: 0.20, // Slower, more visual  
  7.     interval: 1500,  
  8.     click_el: true// ATTENTION  
  9.     onProgress: function(progress){  
  10.         var pr_bar = document.getElementById("pr_bar");  
  11.         pr_bar.style.width = progress.percent + "px";  
  12.         document.getElementById("pr_text").innerHTML = "% " + progress.percent;  
  13.         if(progress.completed)  
  14.             upload(progress.file_tmp_name, progress.file_name, {});  
  15.     },  
  16.     onError: function(error){  
  17.         if(error == PLX.TYPE_ERROR)  
  18.             alert("File type is not allowed!");  
  19.     }  
  20. });  
  21. </script>  
 
% 0

Ajax Image Upload without Refreshing Page using Jquery.

Are you looking for ajax file/image upload and preview without refreshing page using Jquery. I had implemented this ajax form submitting using jquery.form plugin and used Arun Shekar's image cropping PHP code for uploading images. Just five lines of JavaScript code, Using this you can upload files, image and videos.

Ajax Image Upload without Refreshing Page with Jquery and PHP


Download Script     Live Demo

Javascript Code
$("#photoimg").live('change',function(){})- photoimg is the ID name of INPUT FILE tag and $('#imageform').ajaxForm() - imageform is the ID name of FORM. While changing INPUT it calls FORM submit without refreshing page using ajaxForm() method.  
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#photoimg').live('change', function()
{
$("#preview").html('');
$("#preview").html('<img src="loader.gif" alt="Uploading...."/>');
$("#imageform").ajaxForm(
{
target: '#preview'
}).submit();
});
});
</script>

index.php
Contains simple PHP and HTML code. Here $session_id=1 means user id session value.
<?php
include('db.php');
session_start();
$session_id='1'; // User login session value
?>

<form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
Upload image <input type="file" name="photoimg" id="photoimg" />
</form>

<div id='preview'>
</div>

Sample database design for Users.

Users
Contains user details username, password, email, profile_image and profile_image_small etc.
CREATE TABLE `users` (
`uid` int(11) AUTO_INCREMENT PRIMARY KEY,
`username` varchar(255) UNIQUE KEY,
`password` varchar(100),
`email` varchar(255) UNIQUE KEY,
`profile_image` varchar(200),
`profile_image_small` varchar(200),
)

ajaximage.php
Contains PHP code. This script helps you to upload images into uploads folder. Image file name rename into timestamp+session_id.extention
<?php
include('db.php');
session_start();
$session_id='1'; // User session id
$path = "uploads/";

$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024)) // Image size max 1 MB
{
$actual_image_name = time().$session_id.".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
?>

Thursday, 3 May 2012

Ajax and Dynamic Multiple Combo Box Pre-Population if MySQL Data Exists

create the databse


-- phpMyAdmin SQL Dump
-- version 2.9.1.1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Jan 14, 2008 at 06:39 PM
-- Server version: 5.0.27
-- PHP Version: 5.2.0
--
-- Database: `db_ajax`
--

-- --------------------------------------------------------

--
-- Table structure for table `city`
--

CREATE TABLE `city` (
  `id` tinyint(4) NOT NULL auto_increment,
  `city` varchar(50) default NULL,
  `stateid` tinyint(4) default NULL,
  `countryid` tinyint(4) NOT NULL,
  PRIMARY KEY  (`id`)
) TYPE=MyISAM  AUTO_INCREMENT=5 ;

--
-- Dumping data for table `city`
--

INSERT INTO `city` VALUES (1, 'Los Angales', 2, 1);
INSERT INTO `city` VALUES (2, 'New York', 1, 1);
INSERT INTO `city` VALUES (3, 'Toranto', 4, 2);
INSERT INTO `city` VALUES (4, 'Vancovour', 3, 2);

-- --------------------------------------------------------

--
-- Table structure for table `country`
--

CREATE TABLE `country` (
  `id` tinyint(4) NOT NULL auto_increment,
  `country` varchar(20) NOT NULL default '',
  PRIMARY KEY  (`id`)
) TYPE=MyISAM  AUTO_INCREMENT=3 ;

--
-- Dumping data for table `country`
--

INSERT INTO `country` VALUES (1, 'USA');
INSERT INTO `country` VALUES (2, 'Canada');

-- --------------------------------------------------------

--
-- Table structure for table `state`
--

CREATE TABLE `state` (
  `id` tinyint(4) NOT NULL auto_increment,
  `countryid` tinyint(4) NOT NULL,
  `statename` varchar(40) NOT NULL,
  PRIMARY KEY  (`id`)
) TYPE=MyISAM  AUTO_INCREMENT=5 ;

--
-- Dumping data for table `state`
--

INSERT INTO `state` VALUES (1, 1, 'New York');
INSERT INTO `state` VALUES (2, 1, 'Los Angeles');
INSERT INTO `state` VALUES (3, 2, 'British Columbia');
INSERT INTO `state` VALUES (4, 2, 'Toranto');
 








first create the page like this



index.php


<html>
<head>
<title>Roshan's Triple Ajax dropdown code</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script language="javascript" type="text/javascript">
// Roshan's Ajax dropdown code with php
// This notice must stay intact for legal use
// Copyright reserved to Roshan Bhattarai - nepaliboy007@yahoo.com
// If you have any problem contact me at http://roshanbh.com.np
function getXMLHTTP() { //fuction to return the xml http object
  var xmlhttp=false; 
  try{
   xmlhttp=new XMLHttpRequest();
  }
  catch(e) {  
   try{   
    xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
   }
   catch(e){
    try{
    xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e1){
     xmlhttp=false;
    }
   }
  }
    
  return xmlhttp;
    }
 
 function getState(countryId) {  
  
  var strURL="findState.php?country="+countryId;
  var req = getXMLHTTP();
  
  if (req) {
   
   req.onreadystatechange = function() {
    if (req.readyState == 4) {
     // only if "OK"
     if (req.status == 200) {      
      document.getElementById('statediv').innerHTML=req.responseText;      
     } else {
      alert("There was a problem while using XMLHTTP:\n" + req.statusText);
     }
    }    
   }   
   req.open("GET", strURL, true);
   req.send(null);
  }  
 }
 function getCity(countryId,stateId) {  
  var strURL="findCity.php?country="+countryId+"&state="+stateId;
  var req = getXMLHTTP();
  
  if (req) {
   
   req.onreadystatechange = function() {
    if (req.readyState == 4) {
     // only if "OK"
     if (req.status == 200) {      
      document.getElementById('citydiv').innerHTML=req.responseText;      
     } else {
      alert("There was a problem while using XMLHTTP:\n" + req.statusText);
     }
    }    
   }   
   req.open("GET", strURL, true);
   req.send(null);
  }
    
 }
</script>
</head>
<body>
<form method="post" action="" name="form1">
<table width="60%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td width="150">Country</td>
    <td  width="150"><select name="country" onChange="getState(this.value)">
 <option value="">----</option>
 <option value="1">USA</option>
 <option value="2">Canada</option>
        </select></td>
  </tr>
  <tr style="">
    <td>State</td>
    <td ><div id="statediv"><select name="state" >
 <option>----</option>
        </select></div></td>
  </tr>
  <tr style="">
    <td>City</td>
    <td ><div id="citydiv"><select name="city">
 <option>----</option>
        </select></div></td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
</table>
</form>
</body>
</html>
 
 
 
 
create the page for getting the state value from the database (from state table) 

findState.php
 
 
 
<? $country=intval($_GET['country']);
$link = mysql_connect($hostname_petmatch, $username_petmatch, $password_petmatch); //changet the configuration in required
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db($database_petmatch, $link);
$query="SELECT id,statename FROM state WHERE countryid='$country'";
$result=mysql_query($query);

?>
<select name="state" onchange="getCity(<?=$country?>,this.value)">
<option>----</option>
<? while($row=mysql_fetch_array($result)) { ?>
<option value=<?=$row['id']?>><?=$row['statename']?></option>
<? } ?>
</select> 
 
 
findCity.php
 
 
<? $countryId=intval($_GET['country']);
$stateId=intval($_GET['state']);
$link = mysql_connect($hostname_petmatch, $username_petmatch, $password_petmatch); //changet the configuration in required
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db($database_petmatch, $link);
$query="SELECT id,city FROM city WHERE countryid='$countryId' AND stateid='$stateId'";
$result=mysql_query($query);

?>
<select name="city">
<option>----</option>
<? while($row=mysql_fetch_array($result)) { ?>
<option value><?=$row['city']?></option>
<? } ?>
</select>
 
 create the page for getting the city value from the database (from citytable) 
 
 
 Note:- this code for only those who using windows server, 
if you are using linux add php and use echo
for expamle-
 
for windows<? 
 
 =$country?
 
>  
 
for linux 
<?php
 
 echo $country
?> 
 
 
  refernce
 
http://www.experts-exchange.com/Programming/Languages/Scripting/AJAX/Q_26226569.html