Web Development

23Jun

Javascript to Generate a Short Unique ID

Web analytics sometimes requires generating visit ID or visitor ID for storing in the cookies. Below is the code to generate a short enough “unqie” ID for the purpose. It needs to be under 20 characters because Adobe SiteCatalyst / Omniture would only take 20 characters long serialization string. You can control the length by changing the parameter in the slice function.

Math.random().toString(36).slice(-12);

I am planning to use it with the product code to form a unique serialization string. One thing needs to be clarified is that the string is random, but not really “unique”. However, it is close enough. The chance of having two same strings is pretty small if you keep the string length over 10 characters. Appending a timestamp to string would make it unique.

29Jul

Using JQuery and AJAX to Upload Files

I am building a field type to allow users to upload files and images in my CMS. So I need to figure out how to build a nice and neat interface to handle file uploading. Here is a prototype I built which allows users to select a file, and the file will be listed on the page with an upload button next to it. By clicking the upload button, the user can upload the file with a thread in the background without form submission. This is how it looks like after more work has been done to make the prototype look better with Bootstrap. So the prototype code below won’t look as pretty as the screenshot.

jquery upload files

To submit the file in the background, I take a shortcut using jQuery and the jQuery form plugin from malsup.com. So you will need to add the following code in the head section of the web page to load the Javascript library files.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>

The idea is to put a button on the page, and use Javascript to attach a hidden file upload form at the bottom of the page, and draw the file name with a upload button in a canvas layer on the page. Here is the code for the button and canvas.

<input value="select a file" onclick="selectFile()" />
<div id="fileCanvas"></div>

When the button is clicked, we call the selectFile() function to attach the hidden upload form, and click on the hidden file choose button.

var fileIndex = 0;
function selectFile(){
	var form = document.createElement("form");
	form.setAttribute("action", "/upload.php");
	form.setAttribute("style", "display:none;visiblity:hidden");
	form.setAttribute("method", "post");
	form.setAttribute("enctype", "multipart/form-data");
	form.setAttribute("id", "form"+fileIndex);
	form.setAttribute("name", "form"+fileIndex);
	var fileInput = document.createElement("input");
	fileInput.setAttribute("type", "file");
	fileInput.setAttribute("name", "field"+fileIndex);
	fileInput.setAttribute("id", "file"+fileIndex);
	fileInput.setAttribute("onchange", "handleFileSelection('"+fileIndex+"', this.files)");
	form.appendChild(fileInput);
	fileInput.click();
	document.body.appendChild(form);
	fileIndex++;
}

If a file is selected, it will trigger the onchange event of the hidden file choose input and call the function handleFileSelection(). The function will then draw a layer within the canvas to display the selected filename and an upload button.

function handleFileSelection(id, file){
	var canvas = document.getElementById("fileCanvas");
	var fileDiv = document.createElement("div");
	fileDiv.setAttribute("id", "div"+id);
	fileDiv.innerHTML = file[0].name;
	canvas.appendChild(fileDiv);
	// draw buttons
	uploadButton = document.createElement("input");
	uploadButton.setAttribute("type", "button");
	uploadButton.setAttribute("value", "upload");
	uploadButton.setAttribute("id", "uploadButton"+id);
	uploadButton.setAttribute("onclick", "uploadFile('"+id+"')");
	fileDiv.appendChild(uploadButton);
	console.log(id);
	console.log(file);
}

And clicking the upload button will trigger the function uploadFile() to upload the file to a script called upload.php. The PHP script will then save the file if no error and response the result in JSON format so the page can disable the upload button if upload is successful.

$response = array();
if(isset($_FILES)){
	if(count($_FILES) > 0){
		foreach($_FILES as $fieldId => $value){
			if($value['error'] == 0){
				move_uploaded_file($value['tmp_name'], '\\upload\\'.uniqid());
				$response['status'] = 'success';
			}else{
				// see php manual website for error code meaning
				$response['status'] = 'error';
				$response['errorCode'] = $value['error'];
			}
		}
	}else{
		// exceed max post size
		$response['status'] = 'error';
		$response['errorCode'] = -1;
	}
}else{
	$response['status'] = 'error';
	$response['errorCode'] = -10;
}
echo json_encode($response);
© Copyright 2014, All Rights Reserved