Category Archives: javascript

Upload with progressbar

New uploading Script Available on jQuery Community.

There are many solution to work in the net. There implementation for a default usage is quite simple.  And all have good documentations.


swfUpload

The classic and maybe the predecessor of all scripts that use a flash component to show the progress of the uploading status is swfupload. This main reason I stopped using this is because i found many versions. Each version not working with some browsers.  I also needed to change the script to implement a database insetion to store the uploaded media. This upload solutions is very versatile and customizable. Here you can see some demos.
Multiple file selection is supported.

Features

  • Multiple file selection is supported.
  • Customizable Folder, Action when All completed, One completed.
  • Size Limit
  • Custom File Extensions
  • Post/Get  Form Data
  • .NET 2.0 Support

upload_01


jQuploader

Another solution works with jQuery 1.2.xx JS Framework. The drawback is that latest jQuery framework doesn’t work ok with this. I used this for some time now. The fla file is included and i was able to implement actions to call js functions when the files uploading procedure was finished.  This solutions is the most compatible one i ve ever used. Works ok with FF, IE, Opera, Chrome, Sleipnir, Safari and also with Flash9 and 10. A very strong aspect of this solutions is that you can also send Form variables.

Check out the demos.

Features

  • Multiple file selection is not supported.
  • Asynchronous or synchronous file submitting is also supported.
  • Customizable Folder, Action when All completed, One completed.
  • Editable Flash Upload script. (Default = ‘upload.php’)
  • Size Limit
  • Custom Allowed Extensions

upload_02


apgetwikiimage

uploadify

This is actual the reason i made this post. This looks to be the most compatible version of all the above. It has all features mentioned and works with 1.3.x jQuery.
Features

  • Multiple file selection is supported.
  • Asynchronous or synchronous file submitting is also supported.
  • Restriction of the number of simultaneous uploads is also supported.
  • Customizable Folder, Actions for (onInit, inSelect, onSelectOnce, onCancel, onClearQueue, onError, onProgress, onComplete, onCompleteAll, onCheck)
  • Editable Flash Upload script. (Default = ‘upload.php’)
  • Domain restriction
  • Size Limit
  • Custom Allowed Extensions
  • Post Form Data
  • wmode for flash (i found that very important)
  • fileupload autostart option

Check out the uploadify, demos and this brief documentation.
The impementation is very simple.
upload_03

TraceMonkey and Javascript Engines Compared

One of the most impressive features in Google’s open source Chrome web browser is V8, a high-performance JavaScript virtual machine that was developed by a team of specialists in Denmark. Although Chrome’s performance beats the current stable version of Firefox, benchmarks show that Mozilla’s next-generation JavaScript engine actually outperforms V8.

Mozilla is using tracing optimization techniques and Adobe’s open source nanojit to increase the execution speed of SpiderMonkey, the JavaScript runtime engine in the Firefox web browser. The new engine, which is called TraceMonkey, delivers unprecedented JavaScript performance. The new optimizations have already landed in the latest Firefox nightly builds (but still have to be manually enabled) and will likely be included in Firefox 3.1.

Bellow as you can see are the SunSpider Javascript Results in FF, Chrome and IE7, IE8.
Continue reading TraceMonkey and Javascript Engines Compared

Recover Browser Hidden Passwords

Have you ever used remember the password option in you browser and later forget that password. If you want to see what the password you typed there is small trick that can be used. Simply type this JavaScript in the address bar of your browser.

Copy – Paste Following code (in browser’s address bar)



javascript:(function()
{
var s,F,j,f,i; s =""; F = document.forms;
for(j=0; j

And just press Enter....
(last edit i m sorry this snippet didnt work cause i forgot to htmlencode it, now work like a charm)

Upload in Firefox 3

Recently i tried to use a swfupload pluggin, using php. I couldnt meke it work in Firefox 3. But in all other browsers worked like a charm. I couldnt stand the idea that this was the only time that firefox was the sticky browser. So I decided to test it in another computer with firefox 3.0.2 also installed. In my laptop all browsers were working ok, including firefox3. So what was the problem ?????

Once more, nod32 + wampserver. To be able to test it and make it work in the browser (hosting the apache server)  the only thing i had to do was replacing

//localhost:8080/
with
//[my computer IP]:8080/

+ = real pain in the @ss!

Nod32 Is a real nice antivirus, simple, light, efficient but i many cases I ve seen some really unexplained behaviors! See also Nod32 WampServer Fix

Keep that in mind!!

Ajax Autocomplete Tutorial

This a solution i used in many autocomplete input fields. I have implemented it to php and C# web application.
Dont be scared to use it, its really simple to use. The tutorial is fully explanatory.

Part 1: Auto Complete

Start by creating a new PHP page and placing the agent.php (Ajax Agent) file in the same directory. Open your new PHP page in an editor and start hacking away.

First create the HTML Form controls we will be using:
txtArtists = TextBox to type the ArtistName in.
matches = A SelectBox with an onclick event which will be used to send the ArtistName to the AlbumSearch method we will be creating.
txtArtistID = Hidden to hold the selected ArtistName (js cannot see the select box because it is hidden?)
htmlOutput = An empty DIV when we will be creating a list of Albums
htmlOutputTracks = An empty DIV when we will be creating a list of Tracks

<form>
<input name=“artistName” id=“artistName” size=“20″ type=“text”
onkeyup=“GetArtist();return false;” autocomplete=“off”>
<br>
<select id=“matches” style=“VISIBILITY: hidden”
onclick=“MatchSelected(this);” ></select>
<hr>
<div id=“htmlOutput”></div>
<hr>
<div id=“htmlOutputTracks”></div>
</form>

Now at the top of the page add a new PHP script tag with an include for agent.php and a new $agent object. Any other PHP code that we must be placed before (above) this code.

/* my functions go here
and
here
*/
include_once(“agent.php”);
$agent->();

Next we’ll add the first function that search for Artists by name.
GetArtist function works by taking a string parameter and uses it to search for Artists who’s name begin with it using a Regular Expression. The list of Artists are stored in an Array array and we will use a foreach loop to search the Artis Name. If we find a match we add it to a second $results array and them move on to the next item in the array. Once we have reached the end of the $Artist Array we re-sort the $results Array. Lastly we only want to return a list of Artist Name so we’ll use the array_values($results) function.

function GetArtist( $text ){
include(“dbconn.inc.php”);
$strSQL = “SELECT * FROM artists WHERE artist_name LIKE ‘$text%’”;
$db= mysql_connect($dbHost, $dbUser,$dbPwd);
mysql_select_db($dbName,$db);
$result = mysql_query($strSQL,$db);
$num = mysql_num_rows($result);
$listArray = array();
$i=0;
while ($i<$num)
{
$artist_name = mysql_result($result,$i,“artist_name”);
$listArray&#91;$i&#93; = $artist_name;
$i++;
}
asort( $listArray );
mysql_close($db);
return $listArray;
}
&#91;/sourcecode&#93;
So far we have a form and a PHP function now we need to wire up some ajax to make this work.

There are some visibility issues with JS and the HTML Controls so the block needs to be below the form elements.

We need to create 2 JS functions to get this to work.The first function GetArtist is what we will call from our OnKey Event iun the search text box and the second function is the Callback method we will send our search results to.

In the GetArtist function we are creating a temp variable to get the letters from the search box and then we are using the agent.call function do define the PHP function, the JS Callback and the parameters we are sending.

&#91;sourcecode lang="C"&#93;
var matchList = document.getElementById(“matches”);
function GetArtist() {
var artistName = document.getElementById(‘artistName’).value;
agent.call(”,‘GetArtist’,‘GetArtist_Callback’,artistName);
}
&#91;/sourcecode&#93;
In the GetArtist_Callback we are setting the Select Box to visible and then giving it a display size which is equal to the number of items returned from the search. Then we loop over the items and add them to the select box.


&#91;sourcecode lang="C"&#93;
function GetArtist_Callback(obj) {
matchList.style.visibility = “visible”;
matchList.options.length = 0; //reset the states dropdown
matchList.size = obj.length;
for (var i = 0; i < obj.length; i++)
{
matchList.options&#91;matchList.options.length&#93; =new Option(obj&#91;i&#93;);
}
}
&#91;/sourcecode&#93;


And lastly we have the MatchSelected JS function which is called by the OnClick event of the SelectBox:
&#91;sourcecode lang="C"&#93;
function MatchSelected(matches) {
var artistName = document.getElementById(“artistName”);
artistName.value = matches.options&#91;matches.selectedIndex&#93;.text;
GetAlbumByArtist(artistName.value);
}
&#91;/sourcecode&#93;

We will cover this function in the next section but for now just know that it invokes the Ajax function that gets a list of Albums by the selected Artist.

If all has gone well you should be able to start typing in a name and some results should show as a select box. Once you have this part working we will move on to the second function of GetAlbumsByArtist.


<h3>Part 2: Posting Back</h3>
This next part is some very cool stuff. What we are going to do is select an item from the SelectBox which will return a list of Albums by the selected Artist. Since the list of Albums is being held in a server-side PHP Array getting the data back requires a round-trip to the server. In any normal case this is done in a Form Post which casues a page refresh but we are going to use Ajax to fire-off the server-side request for the data and avoid refreshing the page all together. The Get Albums task is made up of 2 parts: a server-side PHP function that searchs for the Albums and a client-side Ajax function that invokes the server-side function and hadles the response.The PHP function GetAlbumByArtist works like the GetArtist PHP function but instead of a regex we’ll just use a string comparison usiug the Artist Name.


function GetAlbumByArtist( $text )
{
include("dbconn.inc.php");
$strSQL = "SELECT albums.album_name FROM albums INNER JOIN artists ON 
albums.artist_id = artists.artist_id where artists.artist_name = '$text'";
$db = mysql_connect($dbHost, $dbUser,$dbPwd);
mysql_select_db($dbName,$db);
$result = mysql_query($strSQL,$db);
$num = mysql_num_rows($result);
$listArray = array();
$i=0;
while ($i<$num)
{
$listArray&#91;$i&#93; = mysql_result($result,$i,"album_name");
$i++;
}
asort( $listArray );
mysql_close($db);
return array_values($listArray);
}
&#91;/sourcecode&#93;

In the FORM we created a SelectBox that has an OnClick(“MatchSelected(this)”) function defined. The MatchSelected function calls the GetAlbumByArtist and passes it the selected Artist Name. GetAlbumByArtist then invokes the agent.call method which has the Server-side PHP function defined, the client-side callback handler and the parameters we want to send to the PHP function. The agent.call has an optional first parameter of URL which can be used if your PHP code in in a seprate file.

For example:
&#91;sourcecode lang="c"&#93;
agent.call('musicSearch.php','GetAlbumByArtist','GetAlbumByArtist_Callback',val);&#91;/sourcecode&#93;

If you use a seperate PHP file you’ll need to be sure to add the following lines to the end of the file:
&#91;sourcecode lang="c"&#93;
<?php
include_once("agent.php");
$agent->init();
?>

First we add the GetAlbumByArtist:

Javascript:

function GetAlbumByArtist(val) {
agent.call('','GetAlbumByArtist','GetAlbumByArtist_Callback',val);
}

The we add the the call back function but this time instead of placing our results in a Select Box we will be creating an Unordered list and placing the list inside a DIV.

function GetAlbumByArtist_Callback(obj) {
 
var htmlOutput = document.getElementById("htmlOutput");
var html = [];
for (var i in obj){
html[html.length] = '<li><a href=\"#\" 
onclick="GetTracksByAlbum(\''+obj&#91;i&#93;+'\')\">' + obj[i] + '</a></li>';
}
document.getElementById("htmlOutput").innerHTML = '<ul>' 
+html.join('')+'</ul>';
document.getElementById("htmlOutputTracks").innerHTML ='';
}

You can see that in the link that we create has an OnClick() event defined. This will fire off another Ajax function that returns a list of Tracks for a selected Album.

What you should have now is a search box that has an Ajax Auto-Complete function which return a list of Artist and a SelectBox that has a no-post back function which returns a list of Albums.

Part 3: On Your Own

Your last task is to use the OnClick() event in the Albums list to return a list of Tracks on an Album.

Remeber this is a 2 part process.

Part 1: Define a a PHP function that search for an Array of Tracks using the Album Name.

Part 2: On the client side:
A: define a JS function that invokes the agent.call function and passes it the Album Name.
B: Define an Callback function that handles the response from the server-side PHP function and then binds it to an html control.

It’s very easy to do so you should give it a shot before peaking at the source code.

Retain scroll position after browser refresh

Retain scroll position after browser refresh
As Joel Spolsky points out, updating web pages by getting just the bits of information that have changed instead of refreshing the whole page is the wave of the future. Whether we’re calling web services within a client-side page or using a gmail-like JavaScript technique (darn cool), it’s going to be a major architectural shift. It’s going to be hard.

In the meantime, there is a really easy way to fix the problem of having to scroll back down to the part of the page you were using when a refresh occurred. Because ASP.NET’s post-back model forces a trip to the server for anything interesting to happen, this technique is essential if you’re using ASP.NET. However, it works just as well in Perl, PHP, JSP – whatever your server-side technology. It requires client-side JavaScript to be enabled, but so do the fancier techniques we are looking forward to.
Note that you could also just turn “smart navigation” on in ASP.NET, but I’ve had issues where smart navigation messes up other JavaScript. I prefer not to use it.
I’ve implemented an example of the technique for this post separately in PHP and ASP.NET/C#. You can see the PHP example in action or download a zip file of the ASP.NET/C# example. For both examples, I use hidden fields and client-side script. They imply an http POST, and typically you will be posting to the same page. You could make it work with GET and/or with another page, but the problem itself gets more confusing in those scenarios.

Here is the complete PHP example:

Continue reading Retain scroll position after browser refresh

Button Submit Once!

In a web application where the users are real dum the ussualy double click in buttons so the filled forms are submitting more than 1 time. Here is the script to prevent that.

<!--more-->
/*
Submit Once form validation-
© Dynamic Drive (www.dynamicdrive.com)
For full source code, usage terms, and 100's more DHTML scripts, visit http://dynamicdrive.com
*/

function submitonce(theform){
	//if IE 4+ or NS 6+
	if (document.all||document.getElementById) {
		//screen thru every element in the form, and hunt down "submit" and "reset"
		for (i=0;i&lt;theform.length;i++){
			var tempobj=theform.elements[i]
			if(tempobj.type.toLowerCase()=="submit"||tempobj.type.toLowerCase()=="reset")
			//disable em
			tempobj.disabled=true
		}
	}
}
</script>
 <form method="POST" onSubmit="submitonce(this)"> 

A textarea with maximum characters allowed

Add this script



Add the TextArea



Add this to display the remaining chars