Thursday 11 October 2012

JSONP with example - Cross browser access

(allows you to make an HTTP request outside your own domain)



* JSONP  is a javascript 

* JSONP  is functions like ajax. 

* JSONP is a replacement for iframe 

* JSONP response page should return response data in json.

Eg : jsonp in javascript      

 request.html in one domain  (HTML/JS  file)


<script type="text/javascript">// <![CDATA[
            function callTheJsonp()
            {
                // the url of the script where we send the asynchronous call
                var url = "http://localhost/utils/jsonp/ajax.php?callback=parseRequest";
                // create a new script element
                var script = document.createElement('script');
                // set the src attribute to that url
                script.setAttribute('src', url);
                // insert the script in out page
                document.getElementsByTagName('head')[0].appendChild(script);
            }
            // this function should parse responses.. you can do anything you need..
            // you can make it general so it would parse all the responses the page receives based on a response field
            function parseRequest(response)
            {
                try // try to output this to the javascript console
                {
                    console.log(response);
                }
                catch(an_exception) // alert for the users that don't have a javascript console
                {
                    alert('product id ' + response.item_id + ': quantity = ' + response.quantity + ' & price = ' + response.price);
                }
            }
// ]]></script>
 <span onclick="callTheJsonp()">click here to make the jsonp call</span>

response.php in another domain:


 <?php
// get the callback function name
    $callback = '';
    if (isset($_GET['callback']))
    {
        $callback = filter_var($_GET['callback'], FILTER_SANITIZE_STRING);
    }
    // make an array with some random values.. so you would see that the results are fetched each time you call this script
    $array = array(
                    'item_id' => rand(1,13),
                    'price' => rand(14,17),
                    'quantity' => rand(18,30)
    );
    // output this array json encoded.. the callback function being the padding (a function available in the web page)
    echo $callback . '('.json_encode($array).');';

SITE TO REFER:

1. http://www.onlinesolutionsdevelopment.com/blog/web-development/javascript/jsonp-example/
2. http://www.ibm.com/developerworks/library/wa-aj-jsonp1/

No comments: