Monday, October 27, 2014

Step By Step Cross Domain Pass Parameter

Objective of this tutorial is helping those who want to create api but having the issue of cross domain problem.

How to Create Client Call API
Step 1:
Create javascript file name myjsfile.js and paste the following codes.

$(function(){
  $('#btn_name').on('click', function(e){
    $.getJSON("http://www.yourotherdomain.com/myapifile.php?jsoncallback=?",
    {
      variable1: "maybe textbox value",
      variable2: "maybe textbox value",
      variable3: "maybe textbox value"
    },
    function(data) {
        var str = data['result'];
        alert(str);
    });
  });
});

Step 2:
Include the following code before </head> tag.

<script src="js/myjsfile.js" type="text/javascript"></script>

You are now able to pass parameter to function from difference domain http://www.yourotherdomain.com/myapifile.php  .


How to Create Server Response
Step 1:
Create php file name myapifile.php and paste the following codes.

<?php
 header("Content-Type: application/json, charset: utf-8;");
 $arr=array();
 $arr['result'] = "Here is your result data";
 echo $_GET['jsoncallback'].'('.json_encode($arr).');';
 exit;
?>

~End~

Notice:
You may get Uncaught SyntaxError: Unexpected token if you did not include $_GET['jsoncallback'].

References:
http://stackoverflow.com/questions/3143698/uncaught-syntaxerror-unexpected-token
http://www.w3resource.com/JSON/JSONP.php