Posts tagged ‘webdesign’

Jeditable JQuery plugin on Rails

The Jeditable JQuery plugin is an awesome piece of javascript code that allows the users of your webpage to just click some text and edit it in place. So instead of having an “edit” page for your data, you let the user edit directly from the “show” page.

The usage of the plugin is very easy, as explained on their homepage. You just wrap the editable text in a div with class “edit” and add the folowing piece of javascript code:

$(document).ready(function() {
$(document).ready(function() {



This will make the text clickable. When the user clicks on it, the text changes to an input field with a submit button, which saves the new data to save.php.


I wanted to use the Jeditable script in my Rails application, but I ran into some difficulties along the way. After some frustrating digging around I came to the following:

I added an update_field action to my controller that allows changing a single value and returns the value of that field:

  # called after editing an item
  # PUT /items/1
  # PUT /items/1.xml
  def update_field
    @item = Item.find(params[:item][:id])
    dc_ds = params[:item][:dc_ds]
    #read and write the DC datastream...
    @dc_ds = => params[:item][:id])
    puts 'params update:'
    pp params

    keys = params[:dc_datastream_solr].keys
    k = keys.first
    #params[:dc_datastream_solr].each_key do |k|
      @dc_ds.send k.to_s+'=',params[:dc_datastream_solr][k]


    render :text => params[:dc_datastream_solr][k]

In the layout of the item we set the javascript AUTH_TOKEN variable so we can correctly set the authenticity token in the requests sent to Rails by JQuery:
<%= javascript_tag "var AUTH_TOKEN = #{form_authenticity_token.inspect};" if protect_against_forgery? %>

And this is the javascript that will work on e.g. <div class=”edit_area” id=”theid” name=”thename” />

//the each is needed because we need to read id and name of each item
$('.edit_area').each(function(i) {
  $(this).editable('./update_field/<>', {
    type	:	'textarea',
    name	:	$(this).attr('name'),
    id		:	$(this).attr('id'),
    cancel	:	'Cancel',
    submit	:	'OK',
    indicator:	'Saving...',
    tooltip	:	'Click to edit...',
    submitdata:	{_method: "put", "item[id]": "<>",authenticity_token: AUTH_TOKEN},
    rows:		10

I iterate explicitly over all the divs on the page with class edit_area so I can set the name and id of this editable object to the name and id attribute of the respective div’s.

The submitdata line does a few things:

submitdata:	{_method: "put", "item[id]": "<>",authenticity_token: AUTH_TOKEN},

_method: "put" is Rails' way of simulating an HTTP PUT verb via an HTTP POST. 

"item[id]": "<>" passes the item's id back to Rails.

authenticity_token: AUTH_TOKEN includes the authenticity token in the request that is sent. 

October 13, 2009 at 7:07 pm 2 comments

Webdesign: show content on top of Flash or Silverlight component

I started playing with JQuery last week and used the Boxy plugin to display a dialog window to the user while disabling all other components. In the background it uses CSS’s z-index property to accomplish this. At least.. almost all components, because as you can see in the video below the flash movie kept appearing on top of the Boxy window. In a later test I noticed the same thing happens for Silverlight components.


Here is how to fix it:


Flash has a “wmode” parameter which you have to set to “opaque” for the z-index style to have an effect. For instance for the Flash JWPlayer:

<script type='text/javascript'> 

	var s1 = new SWFObject('player.swf','IFIPPlayer','400','300','9');








Silverlight has a “windowsless” property which you have to set to ‘true’ for the z-index style to have an effect. For instance for the Silverlight JWPlayer:

<script type=”text/javascript”>
var cnt = document.getElementById(“player_<>/MAM_lowres”);
var src = ‘<%=ActionController::Base.relative_url_root%>/wmvplayer.xaml’;
var cfg = {
height:'<%=defined?(@flashplayer_height) ? @flashplayer_height : 300%>’,
width:'<%=defined?(@flashplayer_width) ? @flashplayer_width : 400%>’,
var ply = new jeroenwijering.Player(cnt,src,cfg);
<script type="text/javascript"> 

	var cnt = document.getElementById("theplayer");

	var src = '/wmvplayer.xaml';

	var cfg = {







	var ply = new jeroenwijering.Player(cnt,src,cfg);	


And a screenshot to prove it 🙂


October 6, 2009 at 11:18 am Leave a comment

File uploads… Flash or Silverlight?

It has been a while, but recently I had to look into Flash again. I was happy to find out Adobe has done some effort to allow the Flash developer to access the local filesystem. This is very useful to implement a file upload (see this example).

In previous versions of Flash, the file upload was about the only thing one could do with local files. Due to security reasons, only Adobe Air (the desktop variant) applications where allowed to read the bytes of a local file. But all this changed quite recently, because in Flash 10 you can finally read a file into a ByteArray and interpret the bytes. This is really cool stuff and will certainly inspire a lot of programmers/designers to come up with innovative applications.

The reason I was excited about it was that I needed an uploader that allows to upload large – like in several gigabytes – files. I thought it would be possible to just read in part of the file and upload that part to the server, and then send the next part. Or send some parts in parallel to speed things up. I already found a nice example online: uploads files in chunks to a server. It needs some modification to work with the new security constraints of Flash 10 (all loader.load calls should go in one function and they should be initiated by a user interaction) but it illustrates splitting a file in chunks very well.

But I hit the wall when looking for a way to load only part of a local file into a ByteArray. As my files will be several gigabytes large, it is impossible to load them entirely into the memory, so I need something to read a part of the file. After some digging around it appears that the Adobe guys didn’t provide this (yet), so I guess my super-uploader for monstrously large files will have to wait :-s

Ok, maybe I should take a look at Silverlight, the Microsoft guys just released the beta of version 3. It didn’t take too many googles to find the open-source Silverlight File Upload project. This Silverlight uploader is pretty amazing, it splits large files into chunks and uploads them in separate POSTs. Serverside code for the platform is included in the project but not necessary (a basic PHP server side is available on the site as well).

As there is not many information on the project’s site, here is some things I learned about it today:

When you download the project, and open it in Visual Studio, you’ll see three projects. The FileUpload project is the client-side, the other two are necessary for the server side. As I’m not interested in these we’ll delete them and use the php server side. Put the php code in the htdocs folder of your Apache, change the upload.php file to upload the file to an existing folder on your harddrive and run it. The Silverlight client generates a TestPage.html which includes the Silverlight component. Because the component expects some parameters to be passed to it, you’ll have to add a <param> tag to it:

<param name="initParams"
value="id=FileUpload,UploadPage=http://localhost/PhpFileUpload/upload.php,MaxConcurrentUploads=1,Filter=Images  (*.jpg;*.gif)|*.jpg;*.gif|All Files (*.*)|*.*,"/>

Now you can just open TestPage.html in a browser and adore the uploading :).

The component will first send a HTTP GET to your server. The server answers with 0 if the file does not exist yet or with the filesize if it does. If the file already exists, the Silverlight component will show a message box asking the user if she wants to overwrite it.

In a second step the actual upload is performed. This is done with a HTTP POST which contains the filename and some other parameters in the URL and the bytes of the file in the body of the POST request. This is very efficient as no parsing of the request body is necessary to extract any fields like filename etc. as would be necessary if the upload was done with a regular multipart/form-data upload.

It is however more difficult than I was hoping for to let the component work together with my Rails application. If anyone knows a good way to write the entire POST body to a file, let me know in the comments :p

edit: found out how to rewrite the method to support multipart upload.

private void writeStringToStream(string s,Stream stream)
    UTF8Encoding encoding = new UTF8Encoding();
    byte[] z = encoding.GetBytes(s);

    for (int i = 0; i < z.Length; i++)

//this method sends the data.
//changed the original code so the POST is multipart with fields. 
private void WriteCallback(IAsyncResult asynchronousResult)
    HttpWebRequest webrequest = (HttpWebRequest)asynchronousResult.AsyncState;

    webrequest.ContentType = "multipart/form-data; boundary=" + MULTIPART_BOUNDARY;

    // End the operation.
    Stream requestStream = webrequest.EndGetRequestStream(asynchronousResult);

    byte[] buffer = new Byte[4096];
    int bytesRead = 0;
    int tempTotal = 0;

    Stream fileStream = resizeStream != null ? (Stream)resizeStream : File.OpenRead();

    string dataName = File.Name;// +".part" + partCounter;
    long fileLen = File.Length;
    long currentLength = ChunkSize;

    //determine content-range
    long currentIndex = BytesUploaded;
    long chunkLength = (currentIndex + ChunkSize > fileLen) ? fileLen - currentIndex : ChunkSize;

    //datafile[file] field
    string theString = "--" + MULTIPART_BOUNDARY + "\r\n";
    theString += "Content-Disposition: form-data; name=\"datafile[file]\"; filename=\"" + dataName + "\"\r\n";
    theString += "Content-Type: binary/octet-stream\r\n";
    theString += "Content-Range: " + currentIndex + "-" + (currentIndex+chunkLength-1) + "/" + fileLen + "\r\n\r\n";

    fileStream.Position = BytesUploaded;
    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0 && tempTotal + bytesRead < ChunkSize && !cancel)
        requestStream.Write(buffer, 0, bytesRead);
        BytesUploaded += bytesRead;
        tempTotal += bytesRead;
        if (UploadProgressChanged != null)
            int percent = (int)(((double)BytesUploaded / (double)FileLength) * 100);
            UploadProgressChangedEventArgs args = new UploadProgressChangedEventArgs(percent, bytesRead, BytesUploaded, FileLength, file.Name);
                UploadProgressChanged(this, args);

    writeStringToStream("\r\n--" + MULTIPART_BOUNDARY + "--\r\n", requestStream);

    // only close the stream if it came from the file, don't close resizestream so we don't have to resize it over again.
    if (resizeStream == null)
    webrequest.BeginGetResponse(new AsyncCallback(ReadCallback), webrequest);

March 31, 2009 at 9:10 pm Leave a comment

Using Eclipse for multi-module Maven2 projects (part 3)

In the last post in this series we used the m2eclipse plugin to create a Maven webapplication in Eclipse. In this post we’ll create a multi-module Maven application.

Continue Reading December 23, 2008 at 4:32 pm 3 comments

Using Eclipse for multi-module Maven2 projects (part 2)

In the first post we installed Eclipse and some plugins. Now we will start using the m2eclipse plugin to open and create Maven projects. This post will show how to create a Maven webapplication in Eclipse.

Continue Reading December 23, 2008 at 3:51 pm Leave a comment

Switch from ASP to PHP

We’re going to switch from asp (with MS Access databases) to php (with a mySQL database) as quick as possible in this tutorial. This file ain’t a full blown PHP tutorial, it just focusses on the important differences between ASP and PHP that might get you stuck for a while.

Continue Reading July 1, 2007 at 12:57 am Leave a comment


Articles to be written…

Twitter – kr3l


RSS Google Reader Shared Stuff

  • An error has occurred; the feed is probably down. Try again later.

RSS Listening to..

  • An error has occurred; the feed is probably down. Try again later.