Pages

Wednesday 27 June 2012

What is sent to server?

How does in place editing work?

Normal flow is this. User clicks text on web page. Block of text becomes a form. User edits contents and presses submit button. New text is sent to webserver and saved. Form becomes normal text again.

Basic usage

While reading you might also want to check live demo. For basic examples we assume to have following html elements.

<div class="edit" id="div_1">Dolor</div>
<div class="edit_area" id="div_2">Lorem ipsum dolor sit amet, consectetuer
adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore
magna aliquam erat volutpat.</div>

There is only one mandatory parameter. URL where browser posts edited content.

 $(document).ready(function() {
     $('.edit').editable('http://www.example.com/save.php');
 });

Code above does several things: Elements with class edit become editable. Editing starts with single mouse click. Form input element is text. Width and height of input element matches the original element. If users clicks outside form changes are discarded. Same thing happens if users hits ESC. When user hits ENTER browser submits text to save.php at www.example.com.

Not bad for oneliner, huh? Lets add some options.

Elements with class edit_area will use textarea as input. They will also have spinning image when data is being submitted to server. Elements with class edit will have text Saving… instead of spinning image. As a bonus lets add tooltip to both. Tooltips are great for informing users what they should do.

 $(document).ready(function() {
     $('.edit').editable('http://www.example.com/save.php', {
         indicator : 'Saving...',
         tooltip   : 'Click to edit...'
     });
     $('.edit_area').editable('http://www.example.com/save.php', {
         type      : 'textarea',
         cancel    : 'Cancel',
         submit    : 'OK',
         indicator : '<img src="img/indicator.gif">',
         tooltip   : 'Click to edit...'
     });
 });

These two examples cover most of needs you usually have. Since most of people like to tweak and hack, lets go forward…


What is sent to server?

When submitting change following data will be POST:ed to server:

 id=elements_id&value=user_edited_content

In some cases you might want to change default parameter names. If you want to data to be POST:ed as:

 elementid=elements_id&newvalue=user_edited_content

you need to add two parameters:
 $(document).ready(function() {
     $('.edit').editable('http://www.example.com/save.php', {
         id   : 'elementid',
         name : 'newvalue'
     });
 });

Usage with Textile, Markdown, ReST, WiKi etc

If the content in edit_area class elements is for example WiKi, Textile or Markdown markup, you do not want to edit the html source. Instead you need the markup source. That can be fetched into input field by passing URL to loadurl parameter.

 $(document).ready(function() {
     $('.edit_area').editable('http://www.example.com/save.php', {
         loadurl  : 'http://www.example.com/load.php',
         type    : 'textarea',
         submit  : 'OK'
     });
 });

In this example load.php should return the markup source not rendered html. However save.php should return rendered html. When saving the browser will display exactly what saving script returns. There is also another option. You can pass markup source in data parameter.

How to use selects?

You can use selects by giving type parameter value of select. Select is built from JSON encoded array. This array can be given using either data parameter or fetched from external URL given in loadurl parameter. Array keys are values for <option> tag. Array values are text shown in pulldown.
JSON encoded array looks like this:

{’E’:‘Letter E’,‘F’:‘Letter F’,‘G’:‘Letter G’, ‘selected’:’F’}

Note the last entry. It is special. With value of ‘selected’ in array you can tell Jeditable which option should be selected by default. Lets make two simple examples. First we pass values for pulldown in data parameter:

 $('.editable').editable('http://www.example.com/save.php', {
     data   : " {'E':'Letter E','F':'Letter F','G':'Letter G', 'selected':'F'}",
     type   : 'select',
     submit : 'OK'
 });

What if you need to generate values for pulldown dynamically? Then you can fetch values from external URL. Lets assume we have following PHP script:

 <?php
 /* http://www.example.com/json.php */
 $array['E'] =  'Letter E';
 $array['F'] =  'Letter F';
 $array['G'] =  'Letter G';
 $array['selected'] =  'F';
 print json_encode($array);
 ?>

Then instead of data parameter we use loadurl:

 $('.editable').editable('http://www.example.com/save.php', {
     loadurl : 'http://www.example.com/json.php',
     type   : 'select',
     submit : 'OK'
 });

But wait! Theres more. Some people are concerned about extra request made to server. You can also combine these two approaches. Let PHP output JSON encoded array directly into JavaScript code.

 <?php
 $array['E'] =  'Letter E';
 $array['F'] =  'Letter F';
 $array['G'] =  'Letter G';
 $array['selected'] =  'F';
 ?>
 $('.editable').editable('http://www.example.com/save.php', {
     data   : '<?php print  json_encode($array); ?>',
     type   : 'select',
     submit : 'OK'
 });

How to style elements?
You can style input element with cssclass and style parameters. First one assumes to be name of a class defined in your CSS. Second one can be any valid style declaration as string. Check the following examples:

 $('.editable').editable('http://www.example.com/save.php', {
     cssclass : 'someclass'
 });

 $('.editable').editable('http://www.example.com/save.php', {
     loadurl : 'http://www.example.com/json.php',
     type    : 'select',
     submit  : 'OK',
     style   : 'display: inline'
 });

Both parameters can have special value of inherit. Setting class to inherit will make form to have same class as it parent. Setting style to inherit will make form to have same style attribute as it parent.
Following example will make word ipsum to be editable with pulldown menu. This pulldown inherits style from <span>. Thus it will be displayed inline.

 Lorem <span class="editable" style="display: inline">ipsum</span> dolor
 sit amet.
 $('.editable').editable('http://www.example.com/save.php', {
     loadurl : 'http://www.example.com/json.php',
     type    : 'select',
     submit  : 'OK',
     style   : 'inherit'
 });

Submitting to function instead of URL
Some people want to control absolutely everything. I want to keep you happy. You can get full control of Ajax request. Just submit to function instead of URL. Parameters passed are same as with callback.

 $('.editable').editable(function(value, settings) {
     console.log(this);
     console.log(value);
     console.log(settings);
     return(value);
  }, {
     type    : 'textarea',
     submit  : 'OK',
 });

Note that function must return string. Usually the edited content. This will be displayed on page after editing is done.

Parameter reference
(String) method: Method to use when submitting edited content. Default is POST. You most likely want to use POST or PUT. PUT method is compatible with Rails.

(Function) callback: Function is called after form has been submitted. Callback function receives two parameters. Value contains submitted form content. Settings contain all plugin settings. Inside function this refers to the original element.

 $('.editable').editable('http://www.example.com/save.php', {
     type     : 'textarea',
     submit   : 'OK',
     callback : function(value, settings) {
         console.log(this);
         console.log(value);
         console.log(settings);
     }
 });

(String) name: Name of the submitted parameter which contains edited content. Default is value.

 $('.editable').editable('http://www.example.com/save.php', {
     name     : 'new_value'
 });

(String) id: Name of the submitted parameter which contains content id. Default is id.

 $('.editable').editable('http://www.example.com/save.php', {
     id     : 'element_id'
 });

(Mixed) submitdata: Extra parameters when submitting content. Can be either a hash or function returning a hash.

$(".editable").editable("http://www.example.com/save.php";, {
   submitdata : {foo: "bar"};
});
$(".editable").editable("http://www.example.com/save.php";, {
   submitdata : function(value, settings) {
       return {foo: "bar"};
   }
});

(String) type: Input type to use. Default input types are text, textarea or select. Additional input types are provided using custom input type API.

(Integer) rows: Number of rows if using textarea.
(Integer) cols: Number of columns if using textarea.
(Integer) height: Height of the input element in pixels. Default is auto. This means height is calculated automatically. Can also be set to none.
(Integer) width: Width of the input element in pixels. Default is auto. This means width is calculated automatically. Can also be set to none.
(Integer) loadurl: Normally content of the form will be same as content of the edited element. However using this parameter you can load form content from external URL.

$(".editable").editable("http://www.example.com/save.php";, {
    loadurl : "http://www.example.com/load.php"
});

Note that id of the edited element will be automatically added to query string. For example loadurl above would become something like:

http://www.example.com/load.php?id=element_id

(Integer) loadtype: Request type to use when using loadurl. Default is GET. You most likely want to use only GET or POST.
(Mixed) loaddata: Extra parameter to add to request when using loadurl. Can be either a hash or function returning a hash.

$(".editable").editable("http://www.example.com/save.php";, {
   loaddata : {foo: "bar"};
});
$(".editable").editable("http://www.example.com/save.php";, {
   loaddata : function(value, settings) {
       return {foo: "bar"};
   }
});

(Mixed) data: Form data passed as parameter. Can be either a string or function returning a string. Can be useful when you need to alter the text before editing.

$(".editable").editable("http://www.example.com/save.php";, {
   data : "Lorem ipsum";
});
$(".editable").editable("http://www.example.com/save.php";, {
    data: function(value, settings) {
      /* Convert <br> to newline. */
      var retval = value.replace(/<br[\s\/]?>/gi, '\n');
      return retval;
    }
});

Miscallenous options
Default action of when user clicks outside of editable area is to cancel edits. You can control this by setting onblur option. Possible values are:

onblur : cancel Clicking outside editable area cancels changes. Clicking submit button submits changes.
onblur : submit Clicking outside editable area submits changes.
onblur : ignore Click outside editable area is ignored. Pressing ESC cancels changes. Clicking submit button submits changes.

Event which starts editing the element can be controlled using option event. All jQuery events are available. Most usable ones are click and dblclick.

Demo
You can test how Jeditable works with live demo.

Creating beautiful and functional tables with DataTables

DataTables has a wealth of features enabled by default (as can be seen in the zero-configuration example) but the example stylesheets that come in the DataTables package are intentionally rather basic, and there will be times you wish to integrate the look and feel of the table a lot more than the default style allows.

Fortunately styling a DataTables table is actually a relatively simple prospect and I’ll show how to build the style up so that your table looks like the one shown below in this post. In this post I’ll use only very basic initialisation of DataTables and concentrate on just nice CSS styling! I’ll be building on the fine work of Inayaili de Leon for this example, and we will end up with a table which looks like this:

The table
First things first – we need a table to show. You’ll no doubt have your own that you wish to style, but in this example I’m going to use some statistics from the Scottish Government about student numbers. Not the most inspiring of information perhaps, but a perfect example of a statistics table which can be presented on a web-site. The basic unstyled and unscripted table looks like this:

<table id="example" border="0" cellpadding="0" cellspacing="0" class="pretty">

    <thead>
        <tr>
            <th rowspan="2">Local authority</th>
            <th colspan="7">Scottish domiciled students in HE</th>
        </tr>
        <tr>
            <th>2005-06</th>
            <th>2006-07</th>
            <th>2007-08</th>
            <th>2008-09</th>
            <th>2009-10</th>
            <th>% change<br>over last year</th>
            <th>% change<br>since 2005-06</th>
        </tr>
    </thead>
    <tfoot>
        <tr>
            <th scope="row">Total</th>
            <td>212.920</td>
            <td>214.860</td>
            <td>206.390</td>
            <td>207.535</td>
            <td>213.210</td>
            <td>2.7</td>
            <td>0.1</td>
        </tr>
    </tfoot>
    <tbody>
        <tr>
            <th scope="row">Aberdeen City</th>
            <td>9.750</td>
            <td>9.850</td>
            <td>9.945</td>
            <td>9.945</td>
            <td>10.080</td>
            <td>1.4</td>
            <td>3.4</td>
        </tr>
        ...
    </tbody>
</table>

Note that because of the TH elements in the table body rows, this example uses DataTables 1.8, where the ability to consume TH elements in the body is a new feature. The full basic page that we are going to work with is available here.

Style and scripting base

In order to preserve our sanity and provide a common baseline for styling the table, I’m going to include the YUI 3 reset stylesheet. This stylesheet basically strips the built-in default styles from a viewing web-browser to give a common starting point for styling across all browsers. This is particularly useful with tables since browsers can often have different defaults styles for various elements. This reset stylesheet is included using the following

HTML:<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/3.3.0/build/cssreset/reset-min.css">

I’ve also added some basic styles to my page in order to provide a little bit of a framework for us to work with (font-size, content width etc).
Next we include and execute the Javascript required to enhance the table with DataTables. This is done by including jQuery and DataTables, followed by initialising DataTables. In this particular case I’ve chosen to use the built-in “full_numbers” pagination style by specifying the sPaginationType parameter. This is all the Javascript that we need to setup our table.

<script type="text/javascript" language="javascript" src="../../media/js/jquery.js"></script>
<script type="text/javascript" language="javascript" src="../../media/js/jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf-8">
    $(document).ready(function() {
        $('#example').dataTable( {
            "sPaginationType": "full_numbers"
        } );
    } );
</script>

To position the various control elements we can float them into position using the following CSS. Note I’ve also included highlighting colours to make it easy to see where each element is. In additional this I’ve included a little padding for the various elements, so they visually fit around the table nicely.

div.dataTables_length {
    float: left;
    background-color: red;
}
div.dataTables_filter {
    float: right;
    background-color: green;
}
div.dataTables_info {
    float: left;
    background-color: blue;
}
div.dataTables_paginate {
    float: right;
    background-color: yellow;
}
div.dataTables_length,
div.dataTables_filter,
div.dataTables_paginate,
div.dataTables_info {
    padding: 6px;
}


Also because we are using floating elements we need to consider clearing them. In this case the table needs to clear the paging length and filtering inputs, while any content that follows the table needs to clear the pagination and information elements. For the former we can use a simple clear: both, but for the latter we can use a self-clearing technique.

table.pretty {
    clear: both;
}
/* Self clearing - */
div.dataTables_wrapper:after {
    content: ".";
    display: block;
    clear: both;
    visibility: hidden;
    line-height: 0;
    height: 0;
}

html[xmlns] .dataTables_wrapper { display: block; }
* html .dataTables_wrapper { height: 1%; }

http://datatables.net/blog/Creating_beautiful_and_functional_tables_with_DataTables for more detailed demo.

Add Pinterest “Pin It” Counter Button To Blogger

<a class=’pin-it-button’ count-layout=’horizontal’ expr:href=’&quot;http://pinterest.com/pin/create/button/?url=&quot; + data:post.url’>Pin It Now!</a>
<a href=’javascript:void(run_pinmarklet())’ style=’margin-left:-93px; width:43px; height:20px; display:inline-block;’/>
<script src=’http://assets.pinterest.com/js/pinit.js’ type=’text/javascript’/>
<script type=’text/javascript’>
function run_pinmarklet() {
var e=document.createElement('script'); e.setAttribute('type','text/javascript');
e.setAttribute('charset','UTF-8');
e.setAttribute('src','http://assets.pinterest.com/js/pinmarklet.js?r=' + Math.random()*99999999);
document.body.appendChild(e);
}
</script>

How to Add ‘Pin It’ Button With Images To Your WordPress Blog Without Plugin

Step 1: Add Pinterest’s javascript

Add the following code to your footer.php file of the theme ( before the </body> close tag ) :
You can get Pinterest’s javascript at Goodies
1
<script type="text/javascript"src="//assets.pinterest.com/js/pinit.js"></script>
Step 2: Add Pin it button to single blog post

Add the following code to single.php file of the theme where you want to show Pin It button:
1
<a href="http://pinterest.com/pin/create/button/?url=<?php the_permalink(); ?>&media=<?php echo catch_that_image() ?>&description=<?php the_title(); ?>" class="pin-it-button" count-layout="horizontal"><img border="0"src="//assets.pinterest.com/images/PinExt.png" title="Pin It" /></a>
Step 3: Get the first image with the functions

Add this code info your functions.php file of the theme:

function catch_that_image() {
  global $post, $posts;
  $first_img = '';
  ob_start();
  ob_end_clean();
  $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i',$post->post_content, $matches);
  $first_img = $matches [1] [0];
  if(empty($first_img)){ //Defines a default image
    $first_img = "/images/default.jpg";
  }
  return $first_img;
}
The end. Thanks for reading my Pin It button tutorial. And a big thanks to Jean-Baptiste Jung.

How to Add Twitter’s Official Tweet Button in WordPress

<script src="http://platform.twitter.com/widgets.js" type="text/javascript"></script>
   <a href="http://twitter.com/share"
      data-url="<?php the_permalink(); ?>"
      data-via="wpbeginner"
      data-text="<?php the_title(); ?>"
      data-related="syedbalkhi:Founder of WPBeginner"
      data-count="vertical">Tweet</a>

Cropping An Image with PHP and the GD Library

Cropping an image with PHP shouldn’t terribly difficult to do and yet when I attempted to do so several months back I was amazed at how little useful documentation PHP offered. Upon Googling the topic I was further amazed but the lack of useful tutorials on the subject. The few I found were overly complicated and didn’t cover simple image cropping. After reading up as much as I could on the subject, and some trial and error, I was able to accomplish my goal of cropping an image with PHP using the GD library.
Just this morning an online friend of mine was struggling with the same issue and twittered for some advice and guidance. I sent them the core of the code I wrote and wished them good luck. I received a quick reply that it worked perfectly for them and apparently ended two days of hair pulling. So I decided I would post the code I sent them here so anyone else who is looking to crop images with PHP and the GD library can do so without having to endure limited documentation and inventing swear words.


// Original image
$filename = 'someimage.jpg';

// Get dimensions of the original image
list($current_width, $current_height) = getimagesize($filename);

// The x and y coordinates on the original image where we
// will begin cropping the image
$left = 50;
$top = 50;

// This will be the final size of the image (e.g. how many pixels
// left and down we will be going)
$crop_width = 200;
$crop_height = 200;

// Resample the image
$canvas = imagecreatetruecolor($crop_width, $crop_height);
$current_image = imagecreatefromjpeg($filename);
imagecopy($canvas, $current_image, 0, 0, $left, $top, $current_width, $current_height);
imagejpeg($canvas, $filename, 100);
// Original image
$filename = 'someimage.jpg';

// Get dimensions of the original image
list($current_width, $current_height) = getimagesize($filename);

// The x and y coordinates on the original image where we
// will begin cropping the image
$left = 50;
$top = 50;

// This will be the final size of the image (e.g. how many pixels
// left and down we will be going)
$crop_width = 200;
$crop_height = 200;

// Resample the image
$canvas = imagecreatetruecolor($crop_width, $crop_height);
$current_image = imagecreatefromjpeg($filename);
imagecopy($canvas, $current_image, 0, 0, $left, $top, $current_width, $current_height);
imagejpeg($canvas, $filename, 100);
Hopefully that helps demonstrate how to simply crop an image with PHP and the GD library.

Set property meta tag in ZEND

$this->doctype(Zend_View_Helper_Doctype::XHTML1_RDFA);
$this->headMeta()->setProperty(‘og:title’, ‘this title is dummy and will changed by dynamic title’);
$this->headMeta()->setName(‘description’, ‘Wel come to archive site you will share all products to facebook’);
$this->headMeta()->setName(‘image’, ‘<img src=”.’.SITE_URL.’/images/fb.png”‘);
$this->headMeta()->appendName(‘keywords’, ‘another test’);

Show Twitter Messages on a web Page

The below code was automagically generated by twitter’s badge utility. You should be able to change “yourtwittername” in the code to your twitter name and stuff it in a block. This should work OK for site wide usage, but if you want each user to have there own, in say their profile page, there needs to be a hook to pull the users info and stuff it in a variable. I know it can be done and there is already a pending patch to do something similar I just don’t have the time right now.

<div id="twitter_div">
<h2>Twitter Updates</h2>
<ul id="twitter_update_list"></ul></div>
<script type="text/javascript" src="http://twitter.com/javascripts/blogger.js"></script>
<script text="text/javascript" src="http://twitter.com/statuses/user_timeline/yourtwittername.json?callback=twitterCallback2&count=5"></script>

Create-bbc-style-news-ticker-Drupal

http://pras.net.np/blogs/create-bbc-style-news-ticker-drupal
demo:
Welcome to views ticker (drupal module) demo page.
Project: http://drupal.org/project/views_ticker
You can see 5 tickers of different style working on this page. YES! I got them all working on the same page — Horizontal scroll, Vertical scroll, vTicker, BBC & Fade styles.
Use fields format in the views, and select fields that are not too long. Mark fields as inline if it doesn\\\’t seem to work properly (this fixes few issues – particularly with horizontal scroll).
http://viewsticker.inettity.com/