Tuesday 21 May 2013

jQuery Plugin to display In line related info


A free light weight jQuery plugin that enables you to display related information with the hovered label, link, or any html element of your choice.
What is so cool about this plugin!

·         Smoothly fades the name into a hovered card (in place).
·         Uses minimum css and no external stylesheets to download.
·         Full control over html to be displayed.
·         Comes with built in Twitter and Facebook hovercard.
·         Supports callback functions on hover in and hover out.
·         New! Auto adjust on the edges of viewport
·         Built in Twitter and Facebook Hovercard
When should you use hovercard:
A hovercard comes handy when displaying Person bio, Book author and price, Loading related information with Ajax, Editing in place, and what not! Check out the following demos to see some of this stuff in action :)
$('#demo-basic').hovercard({

    detailsHTML: $('#hiddenDiv').html()
});
Example : 

<label id="demo-facebook" data-hovercard="8936834181"> jQuery </label> by John Resig is a cross-browser JS library designed to simplify
the client-side scripting of HTML. It was released in January of 2006 at BarCamp NYC. Used by over 46% of the 10,000
most visited websites, it's the most popular JavaScript library in use today. </p>    

//plugin script for facebook hovercard---
<script type="text/javascript">
$(document).ready(function () {   
     $('#demo-facebook').hovercard({
           showFacebookCard: true,          
           width: 350
      });
});
</script>


Good Luck..

Friday 3 May 2013

Difference between JSON and JSONP


Ajax - "Asynchronous Javascript and XML". Ajax loosely defines a set of technologies to help make web applications present a richer user experience. Data updating and refreshing of the screen is done asynchronously using javascript and xml (or json or just a normal http post).

JSON - "Javascript Object Notation". JSON is like xml in that it can be used to describe objects, but it's more compact and has the advantage of being actual javascript. An object expressed in JSON can be converted into an actual object to be manipulated in javascript code.

By default, Ajax requests have to occur in the same domain of the page where the request originates. JSONP - "JSON with padding" - was created to allow you to request JSON resources from a different domain. (CORS is a newer and better alternative to JSONP.)

REST - "Representational State Transfer". Applications using REST principles have a Url structure and a request/response pattern that revolve around the use of resources. In a pure model, the HTTP Verbs Get, Post, Put and Delete are used to retrieve, create, update and delete resources respectively. Put and Delete are often not used, leaving Get and Post to map to select (GET) and create, update and delete (POST)

Example : 

<!DOCTYPE html>
<html>
<head>
  <style>img{ height: 100px; float: left; }</style>
  <script src="http://code.jquery.com/jquery-1.5.js"></script>
</head>
<body>
  <div id="images">
    
  </div>
  <script>
      {
        artistCode: "421",
        apikey: "[Your API key here]" ,
        format: "jsonp"
      },
      function(data) {
        $.each(data.response.tracks.track, function(i,track){
         $("<img/>").attr({
           src: track.images.img_256,
           alt: track.name
         }).appendTo("#images");
        });
      });
  </script>

</body>
</html>


Good Luck...!!!

HTML5 Web Storage


HTML5 web storage, a better local storage than cookies.

What is HTML5 Web Storage?

With HTML5, web pages can store data locally within the user's browser.
Earlier, this was done with cookies. However, Web Storage is more secure and faster. The data is not included with every server request, but used ONLY when asked for. It is also possible to store large amounts of data, without affecting the website's performance.
The data is stored in key/value pairs, and a web page can only access data stored by itself.
There are several reasons to use client-side storage.
·         First, you can make your app work when the user is offline, possibly sync'ing data back once the network is connected again.
·         Second, it's a performance booster; you can show a large corpus of data as soon as the user clicks on to your site, instead of waiting for it to download again.
·         Third, it's an easier programming model, with no server infrastructure required. Of course, the data is more vulnerable and the user can't access it from multiple clients, so you should only use it for non-critical data, in particular cached versions of data that's also "in the cloud".
See "Offline": What does it mean and why should I care? for a general discussion of offline technologies, of which client-side storage is one component.

Browser Support

Web storage is supported in Internet Explorer 8+, Firefox, Opera, Chrome, and Safari.
Note: Internet Explorer 7 and earlier versions, do not support web storage.

localStorage and sessionStorage 

There are two new objects for storing data on the client:
  • localStorage - stores data with no expiration date
  • sessionStorage - stores data for one session
Before using web storage, check browser support for localStorage and sessionStorage:
if(typeof(Storage)!=="undefined")
  {
  // Yes! localStorage and sessionStorage support!
  // Some code.....
  }
else else
  {
  // Sorry! No web storage support..
}

The localStorage Object

The localStorage object stores the data with no expiration date. The data will not be deleted when the browser is closed, and will be available the next day, week, or year.

Example

localStorage.lastname="Smith";
document.getElementById("result").innerHTML="Last name: "
+ localStorage.lastname;
Example explained:
  • Create a localStorage key/value pair with key="lastname" and value="Smith"
  • Retrieve the value of the "lastname" key and insert it into the element with id="result"
Tip: Key/value pairs are always stored as strings. Remember to convert them to another format when needed.
The following example counts the number of times a user has clicked a button. In this code the value string is converted to a number to be able to increase the counter:
if (localStorage.clickcount)
  {
  localStorage.clickcount=Number(localStorage.clickcount)+1;
  }
else
  {
  localStorage.clickcount=1;
  }
document.getElementById("result").innerHTML="You have clicked the button " + localStorage.clickcount + " time(s).";

The sessionStorage Object

The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the browser window.
The following example counts the number of times a user has clicked a button, in the current session:

Example

if (sessionStorage.clickcount)
  {
  sessionStorage.clickcount=Number(sessionStorage.clickcount)+1;
  }
else
  {
  sessionStorage.clickcount=1;
  }
document.getElementById("result").innerHTML="You have clicked the button " + sessionStorage.clickcount + " time(s) in this session.";


Good Luck...!!!

HTML5 Web Workers


A web worker is a JavaScript running in the background, without affecting the performance of the page.

What is a Web Worker?

When executing scripts in an HTML page, the page becomes unresponsive until the script is finished.
A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting the performance of the page.
You can continue to do whatever you want: clicking, selecting things, etc., while the web worker runs in the background.

“Web Workers allow for long-running scripts that are not interrupted by scripts that respond to clicks or other user interactions, and allows long tasks to be executed without yielding to keep the page responsive.”

Check Web Worker Support


if(typeof(Worker)!=="undefined")
  {
  // Yes! Web worker support!
  // Some code.....
  }
else
  {
  // Sorry! No Web Worker support..
  }

Create a Web Worker File

Now, let's create our web worker in an external JavaScript.
Here, we create a script that counts. The script is stored in the "demo_workers.js" file:
var i=0;

function timedCount()
{
i=i+1;
postMessage(i);
setTimeout("timedCount()",500);
}
The important part of the code above is the postMessage() method - which is used to posts a message back to the HTML page.
Note: Normally web workers are not used for such simple scripts, but for more CPU intensive tasks.

Create a Web Worker Object

Now that we have the web worker file, we need to call it from an HTML page.
The following lines checks if the worker already exists, if not - it creates a new web worker object and runs the code in "demo_workers.js":

if(typeof(w)=="undefined"){
  w=new Worker("demo_workers.js");}

Then we can send and receive messages from the web worker.
Add an "onmessage" event listener to the web worker.(Once the Web Worker is spawned, communication between web worker and its parent page is done using the postMessage() method. Depending on your browser/version, postMessage() can accept either a string or JSON object as its single argument.)

w.onmessage=function(event){
document.getElementById("result").innerHTML=event.data;};

When the web worker posts a message, the code within the event listener is executed. The data from the web worker is stored in event.data.

Terminate a Web Worker

When a web worker object is created, it will continue to listen for messages (even after the external script is finished) until it is terminated.
To terminate a web worker, and free browser/computer resources, use the terminate() method:
w.terminate();


Good Luck..!!!




Differences between Get Vs Post


GET vs POST

·         A GET request is used to get data from the server.
·         A POST request is used for modifying data on the server.

When to use GET

If the processing of a form is idempotent (i.e. it has no lasting observable effect on the state of the world), then the form method should be GET. Many database searches have no visible side-effects and make ideal applications of query forms.

Characteristics of GET:

·         Use GET for safe actions and POST for unsafe actions.
·         GET requests can be cached
·         GET requests can remain in the browser history
·         GET requests can be bookmarked
·         GET requests can be distributed & shared
·         GET requests can be hacked

When to use POST

If the service associated with the processing of a form has side effects (for example, modification of a database or subscription to a service), the method should be POST.
Use POST when dealing with long requests – if you’re sending large amounts of data, or sensitive data over HTTPS, you will want to use POST. Some browser such as Internet Explorer place a limit on the URL string so this may break the action of some forms if you use GET.

You may consider using POST for the following actions:

·         Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles
·         Providing a block of data, such as the result of submitting a form, to a data-handling process
·         Extending a database through an append operation
·         Annotation of existing resources

Good Luck…

Difference between $.ajax() and $.get() and $.load()


·         $.ajax() is the most configurable one, where you get fine grained control over HTTP headers and such. You're also able to get direct access to the XHR-object using this method. Slightly more fine-grained error-handling is also provided. Can therefore be more complicated and often unecessary, but sometimes very useful. You have to deal with the returned data yourself with a callback.

·         $.get() is just a shorthand for $.ajax() but abstracts some of the configurations away, setting reasonable default values for what it hides from you. Returns the data to a callback. It only allows GET-requests so is accompanied by the $.post() function for similar abstraction, only for POST

·         .load() is similar to $.get() but adds functionality which allows you to define where in the document the returned data is to be inserted. Therefore really only usable when the call only will result in HTML. It is called slightly differently than the other, global, calls, as it is a method tied to a particular jQuery-wrapped DOM element. Therefore, one would do: $('#divWantingContent').load(...)

·         It should be noted that all $.get(), $.post(), .load() are all just wrappers for $.ajax() as it's called internally.

Good Luck...!!!