Thursday, February 23, 2012

AJAX Cross domain with PHP and PL/SQL using JSONP

Currently, if you try to use a regular ajax call cross domain there is a same origin policy that will not allow you to do it. One way around this is using JSONP (JavaScript Object Notation with Padding). The name makes no sense and trying to think what the padding means is useless. But this will allow cross domain communication and that is the important part. On my P drive I made a PHP page like this:

<?php
header("content-type: text/javascript");

    if(isset($_GET['name']) && isset($_GET['callback']))
    {
        $obj->name = $_GET['name'];
        $obj->message = "Hello " . $obj->name;

        echo $_GET['callback']. '(' . json_encode($obj) . ');';
    }
?>



The JSON is $obj, and the encoding will format it to a Javascript object notation to allow accessing $obj name and message.

Next, the PL/SQL page:

create or replace procedure ajax_test is
begin

  htp.prn('
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>JQuery JSONP</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
    <script>
    $(document).ready(function(){

        $("#useJSONP").click(function(){
            $.ajax({
                url: "http://www.wou.edu/~braken/test_stuff.php",
                data: {name: "Chad"},
                dataType: "jsonp",
                jsonp: "callback",
                jsonpCallback: "jsonpCallback",
                success: function(){
                    alert("success");
                }
            });
        });

    });

    function jsonpCallback(data){
        $("#jsonpResult").text(data.message);
    }
    </script>
  </head>

  <body>
    <input type="button" id="useJSONP" value="Use JSONP"></input><br /><br />
    <span id="jsonpResult"></span>
  </body>
</html>
  '
);
end ajax_test;



With this, as soon as you hit the button, it will call the http page and send it the data "Chad" then the PHP page will get that name and make a $obj->name and message, and then will encode it in JSON. Then it will call the function named in jsonpCallback in the ajax call which will take the data and display it. Notice, the message, since it was encoded in JSON, can be accessed as data.message which is the $obj from the PHP page.

No comments:

Post a Comment