Category Archives: JavaScript

dSlider – Hierarchy Slider (Jquery Plugin)

I need a slider for folder hierarchy. but I couldn’t find any plugin for that.

So, I made it very simply, and now I’m sharing. I hope it could help someone :)

dSlider Screen Shot

Download Plugin 

View Demo

 

Posted in JavaScript, Tech Note | Tagged , | Leave a comment

To move page with POST data using Javascript or Jquery

var url = "/Product/Delete/";

//Pure Javascript
var postForm = document.createElement("form");
postForm.method = "post";
postForm.action = url;
var input = document.createElement("input");
input.setAttribute("name", "ID");
input.setAttribute("value", ID);
postForm.appendChild(input);
document.body.appendChild(postForm);
postForm.submit();
//Using Jquery
$("body").append($("
") .attr({ "action": url, "method": "post", "id" : "postForm" }) .append($(' ') .attr({ "type": "hidden", "name": "ID", "value": ID }) ) .append($(' ') .attr({ "type": "hidden", "name": "Name", "value": "Mark Song" }) ) ).find("#postForm").submit();

For the Jquery case, please replace these words. (‘/’ is not showing in the code block..)

<form> => <form/>

<input> => <input/>

Posted in JavaScript, Tech Note | Tagged | 1 Comment

Uploading File using Ajax and receiving binary data in Asp.net (C#)

In this post, I will show you how to upload a file using Ajax (Asynchronous JavaScript and XML) and receive the binary data in Asp.net C#. And it is ultra simple!

1. HTML

2. JS

function uploadfile(){
    var bannerImage = $("#bannerImage").val();

    if (bannerImage) {
            var file = document.getElementById('bannerImage').files[0];
            var formData = new FormData();
            formData.append(file.name, file);

            var xhr = new XMLHttpRequest();
            var url = "/Category/UpdateBannerImage";
            xhr.open('POST', url, true);
            xhr.onload = function (e) {
                var response = $.parseJSON(e.target.response);
                console.log(response.fileName);
            };

           xhr.send(formData);  // multipart/form-data

    }
}

(Sending Binary Data)

3. C#, Receiving binary data

public JsonResult UpdateBannerImage()
{
    HttpPostedFileBase bannerImage = Request.Files[0] as HttpPostedFileBase;
    if (bannerImage != null && bannerImage.ContentLength > 0)
    {
	var fileName = Path.GetFileName(bannerImage.FileName);
	fileName = Regex.Replace(fileName, @"\s|\$|\#\%", "");
	var path = Path.Combine(Server.MapPath("~/images/category_banners"), fileName);
	bannerImage.SaveAs(path);

	return Json(new { success = false ,error = false, message = "Image has been updated successfully", fileName = fileName });
    }
    else
    {
	return Json(new { success = true, error = "File is empty" });
    }
}
Posted in ASP.NET, JavaScript, Tech Note | Tagged , , , | 2 Comments

Javascript Class Example

var studentData = {
	ver : '0.1',
	students : new Array(),
	addStudent : function(id,name){
		this.students[id] = new Array();
		this.students[id]['name'] = name;
	},
	getName : function(id){
		return this.students[id]['name'];
	},
	setScore : function(id,subject,score){
		this.students[id][subject] = score;		
	},
	getScore : function(id,subject){
		return this.students[id][subject];
	},
	getStudentSize : function(){
		var cnt = 0;
		for(var key in this.students){
			cnt++;
		}
		return cnt;
	},
	getVersion : function(){
		return this.ver;
	}
}

function setStudent(){
	studentData.addStudent('a','Mark');
	studentData.addStudent('b','Kim');
	studentData.addStudent('b','Park ');
	//alert(studentData.getName('a')); // Output : Mark
	//alert(studentData.getStudentSize()); // Output : 3
	//alert(studentData.ver); // Output : 0.1
	alert(studentData.getVersion()); // Output : 0.1
}
Posted in JavaScript, Tech Note | Tagged , , | Leave a comment

Javascript Undefined check

if(typeof myVar == ‘undefined’){

console.log(‘myVar is not defined!’);

}

Posted in JavaScript, Tech Note | Tagged , , | Leave a comment

Serialize with Jquery and Unserialize with PHP

//JS (Jquery)

var serializedData = $('#myForm').serialize();

$.post(
	'getSerializedData.php',
	{data:serializedData},
	function(data){
	}
)

// PHP

$serializedData = $_POST['data'];
$unserializedData = array();

parse_str($serializedData,$unserializedData);

print_r($unserializedData);
Posted in JavaScript, PHP, Tech Note | Tagged , , , | 6 Comments

Using Radix when using parseInt


console.log(parseInt('50')); //output 50
console.log(parseInt('050')); //output 40 


//Uisng Radix

console.log(parseInt('050',10)); //output 50
console.log(parseInt('050',8)); //output 40
Posted in JavaScript, Tech Note | Tagged , | 3 Comments

JavaScript base64_encode

I had to use KOREAN word in the URL.

but Codeigniter does not allow to use that word. so I need to encode the word using javascript because the form send from javascript.

while googling google, I found very useful javascript library, php.js

php.js enable to use most of php functions in javascript. it is awesome!

http://phpjs.org/pages/home

My usage for base64_encode,

<script type='text/javascript'>
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// For base64_encode //////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

function utf8_encode (argString) {
// http://kevin.vanzonneveld.net
// +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// +   improved by: sowberry
// +    tweaked by: Jack
// +   bugfixed by: Onno Marsman
// +   improved by: Yves Sucaet
// +   bugfixed by: Onno Marsman
// +   bugfixed by: Ulrich
// +   bugfixed by: Rafal Kukawski
// *     example 1: utf8_encode('Kevin van Zonneveld');
// *     returns 1: 'Kevin van Zonneveld'

if (argString === null || typeof argString === "undefined") {
return "";
}

var string = (argString + ''); // .replace(/\r\n/g, "\n").replace(/\r/g, "\n");
var utftext = "",
start, end, stringl = 0;

start = end = 0;
stringl = string.length;
for (var n = 0; n < stringl; n++) {
var c1 = string.charCodeAt(n);
var enc = null;

if (c1 < 128) {
end++;
} else if (c1 > 127 && c1 < 2048) {
enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
} else {
enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
}
if (enc !== null) {
if (end > start) {
utftext += string.slice(start, end);
}
utftext += enc;
start = end = n + 1;
}
}

if (end > start) {
utftext += string.slice(start, stringl);
}

return utftext;
}

function base64_encode (data) {
// http://kevin.vanzonneveld.net
// +   original by: Tyler Akins (http://rumkin.com)
// +   improved by: Bayron Guevara
// +   improved by: Thunder.m
// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// +   bugfixed by: Pellentesque Malesuada
// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// -    depends on: utf8_encode
// *     example 1: base64_encode('Kevin van Zonneveld');
// *     returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
// mozilla has this native
// - but breaks in 2.0.0.12!
//if (typeof this.window['atob'] == 'function') {
//    return atob(data);
//}
var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
ac = 0,
enc = "",
tmp_arr = [];

if (!data) {
return data;
}

data = this.utf8_encode(data + '');

do { // pack three octets into four hexets
o1 = data.charCodeAt(i++);
o2 = data.charCodeAt(i++);
o3 = data.charCodeAt(i++);

bits = o1 << 16 | o2 << 8 | o3;

h1 = bits >> 18 & 0x3f;
h2 = bits >> 12 & 0x3f;
h3 = bits >> 6 & 0x3f;
h4 = bits & 0x3f;

// use hexets to index into b64, and append result to encoded string
tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
} while (i < data.length);

enc = tmp_arr.join('');

switch (data.length % 3) {
case 1:
enc = enc.slice(0, -2) + '==';
break;
case 2:
enc = enc.slice(0, -1) + '=';
break;
}

return enc;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

alert(base64_encode('안녕'));
</script>


<?php
echo base64_decode('7JWI64WV');
// output: 안녕
?>
Posted in JavaScript, Tech Note | Tagged , , , | 1 Comment

Use Jquery with the other library.

var JQ = jQuery.noConflict(true); // Now use ‘JQ’ instead of ‘$’

JQ(function(){
JQ(“#testDiv”).css(‘color’,’green’);
});

^o^

Posted in JavaScript | Tagged | Leave a comment

Check whether the function is existed before call

if(typeof window.pauseChicken== 'function') {
  // function exists, so we can now call it
  pauseChicken();
}
Posted in JavaScript | Leave a comment