Pacecode Blog Tips, Scripts and More…

1Sep/110

Cross-domain communications with JSONP using JavaScript and jQuery!

Asynchronous JavaScript and XML (Ajax) is the key technology driving the new generation of Web sites, popularly termed as Web 2.0 sites.Ajax allows for data retrieval in the background without interfering with the display and behavior of the Web application. Data is retrieved using the XMLHttpRequest function, which is an API that lets client-side JavaScript make HTTP connections to remote servers.

This approach, however, does not allow cross-domain communication because of restrictions imposed by the browser. If you try to request data from a different domain, you will get a security error.

The same-origin policy limitations:

The same-origin policy prevents a script loaded from one domain from getting or manipulating properties of a document from another domain. That is, the domain of the requested URL must be the same as the domain of the current Web page.

How to resolve?

Technique 1:

One relatively simple way to overcome this limitation is to have the Web page request data from the Web server it originates from, and to have the Web server behave as a proxy relaying the request to the actual third-party servers. Although widely used, this technique isn’t scalable.

Technique 2:

Another way is to use frame elements to create new areas in the current Web page, and to fetch any third-party content using GET requests. After being fetched, however, the content in the frames would be subject to the same-origin policy limitations.

Technique 3 (Using JSONP):

A more promising way to overcome this limitation is to insert a dynamic script element in the Web page, one whose source is pointing to the service URL in the other domain and gets the data in the script itself. When the script loads, it executes.
It works because the same-origin policy doesn’t prevent dynamic script insertions and treats the scripts as if they were loaded from the domain that provided the Web page. But if this script tries to load a document from yet another domain, it will fail. Fortunately, you can improve this technique by adding JavaScript Object Notation (JSON) to the mix.

JSONP Using Javasript:

Your client-side code:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

<html lang="en">
<head>
<title>jsonp</title>
</head>
<body>
<span></span>
<script>
//this function is the callback, it needs to be a global variable
function readResponse(response){
document.getElementsByTagName('SPAN')[0].innerHTML = response.time + ' is from  php file';
console.log(response);
}
(function(){
//note the "readResponse" at the end
var src = 'http://www.your-cross-domain.com/index.php?id=18&callback=readResponse',
script = document.createElement('SCRIPT');
script.src = src;
document.body.appendChild(script);
})();

</script>
</body>
</html>

Your server-side coding:

<?php
$array = array("time"=>time());
if($_GET['callback']){
header('Content-type: application/json');
echo $_GET['callback']."(".json_encode($array).")";
exit();
}
?>

JSONP using jQuery:

<!DOCTYPE html>
<html>
<head>
<style>img{ height: 100px; float: left; }</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div id="images">
</div>
<script>
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", {
tags: "cat",
tagmode: "any",
format: "json"
}, function (data) {
$.each(data.items, function (i, item) {
$("<img/>").attr("src", item.media.m).appendTo("#images");
if (i == 3) return false;
});
});
</script>
</body>
</html>

24Apr/100

Show Password Text in Password Input Field

As you know, the user login box of the website contains the following fields username and password. Furthermore, most of them put the “Username” inside user name field and “********” inside password field to save the space within designing.In this post I’ll show you how to show “Password” text in the password field. It doesn’t actually does so but this tips will make it looks like so.

How it's done

The type of field cannot be changed with Javascript from type="text" to type="password" so there are actually two fields for the password: a regular password field, and a second plain text field with the default "Password" value.

When the page is loaded the CSS makes the plain text field hidden. Then the jQuery / js makes the password field hidden and the plain text field visible. It's best to do it this way so if Javascript is not enabled (or there's a Javascript error which causes the rest of the script to stop running) then the user still has a regular password field with obscured text.

When the user clicks the plain text field, the jQuery / JS code makes the plain text field hidden, the password field visible and puts focus on the password field. On blur, if the password field contains an empty value the plain text field is restored as the visible one to show the default value.

Demo

Download (Both jQuery type and js type)