55

I am facing the same-origin policy problem, and by researching the subject, I found that the best way for my particular project would be to use JSONP to do cross-origin requests.

I've been reading this article from IBM about JSONP, however I am not 100% clear on what is going on.

All I am asking for here, is a simple jQuery>PHP JSONP request (or whatever the terminology may be ;) ) - something like this (obviously it is incorrect, its just so you can get an idea of what I am trying to achieve :) ):

jQuery:

$.post('http://MySite.com/MyHandler.php',{firstname:'Jeff'},function(res){
    alert('Your name is '+res);
});

PHP:

<?php
  $fname = $_POST['firstname'];
  if($fname=='Jeff')
  {
    echo 'Jeff Hansen';
  }
?>

How would I go about converting this into a proper JSONP request? And if I were to store HTML in the result to be returned, would that work too?

Jeff
  • 12,085
  • 12
  • 82
  • 152

7 Answers7

90

When you use $.getJSON on an external domain it automatically actions a JSONP request, for example my tweet slider here

If you look at the source code you can see that I am calling the Twitter API using .getJSON.

So your example would be: THIS IS TESTED AND WORKS (You can go to http://smallcoders.com/javascriptdevenvironment.html to see it in action)

//JAVASCRIPT

$.getJSON('http://www.write-about-property.com/jsonp.php?callback=?','firstname=Jeff',function(res){
    alert('Your name is '+res.fullname);
});

//SERVER SIDE
  <?php
 $fname = $_GET['firstname'];
      if($fname=='Jeff')
      {
          //header("Content-Type: application/json");
         echo $_GET['callback'] . '(' . "{'fullname' : 'Jeff Hansen'}" . ')';

      }
?>

Note the ?callback=? and +res.fullname

Liam Bailey
  • 5,879
  • 3
  • 34
  • 46
21

First of all you can't make a POST request using JSONP.

What basically is happening is that dynamically a script tag is inserted to load your data. Therefore only GET requests are possible.

Furthermore your data has to be wrapped in a callback function which is called after the request is finished to load the data in a variable.

This whole process is automated by jQuery for you. Just using $.getJSON on an external domain doesn't always work though. I can tell out of personal experience.

The best thing to do is adding &callback=? to you url.

At the server side you've got to make sure that your data is wrapped in this callback function.

ie.

echo $_GET['callback'] . '(' . $data . ')';

EDIT:

Don't have enough rep yet to comment on Liam's answer so therefore the solution over here.

Replace Liam's line

 echo "{'fullname' : 'Jeff Hansen'}";

with

 echo $_GET['callback'] . '(' . "{'fullname' : 'Jeff Hansen'}" . ')';
Ewout Kleinsmann
  • 1,287
  • 1
  • 9
  • 20
  • I am choking on the last part - why are you doing the '('.$data...? – Jeff Jul 24 '11 at 19:28
  • 1
    As I said your data has to be wrapped into a Javascript function. Liam's example won't work. The actual response should look like this: callbackFunction({"fullname": "Jeff Hansen"}) – Ewout Kleinsmann Jul 24 '11 at 19:32
  • Sorry, but you are wrong, yes you need the ?callback= on the url, but if you just make it ?callback=? you can send your data in JSON in the second parameter. I know because I have done it. – Liam Bailey Jul 24 '11 at 19:32
  • 1
    You can send it, but you can't receive it without adding the wrapper callback function. EDIT: You're talking about the client-side in jQuery, but I'm talking about the server-side in PHP which needs adjusting. – Ewout Kleinsmann Jul 24 '11 at 19:35
  • @Ewout - I adjusted my PHP code, but it did not return either. Are you sure its parantheses and not curly brackets? – Jeff Jul 24 '11 at 19:47
  • @Ewout - Yup, did before I saw your edit tho, but I read your "callbackFunction({...." :) – Jeff Jul 24 '11 at 19:50
  • The hard part is now to decide which one of you get the mark! You both contributed equally IMO. – Jeff Jul 24 '11 at 19:51
  • @Ewout - I was not getting any error, nothing happend - however it is fixed now :) – Jeff Jul 24 '11 at 19:53
  • I edited Liam's answer. Once the edit is peer reviewed you can accept that answer, as it will be a complete example for future references. – Ewout Kleinsmann Jul 24 '11 at 19:55
  • We were both right, the second parameter needs changing in the getJSON call as well. I have tested it and got it working and posted working code – Liam Bailey Jul 24 '11 at 20:05
  • @Liam: an object as second parameter for a getJSON call should actually be perfectly fine. Are you sure your code is working? I find that hard to believe since you're using curly brackets instead of parantheses to wrap your callback function. – Ewout Kleinsmann Jul 24 '11 at 20:12
  • Yes, it works I tried with parens, it didn't work, then changed to curly brackets and it works like a dream. Yes object is fine for second param too, but not how I originally had it. – Liam Bailey Jul 24 '11 at 20:17
  • Looks like the 3rd answer uses square brackets - could it be all bracket types are valid? – Jeff Jul 24 '11 at 20:23
  • You can go to http://smallcoders.com/javascriptdevenvironment.html to see it in action – Liam Bailey Jul 24 '11 at 20:24
  • Actually it can't be. Only parantheses should work since the callback function is a Javascript function which has to be called. @Liam could you show me your working example with curly brackets? I'm quite curious how that's working... EDIT: I see your example, but you are using parantheses and no curly brackets... – Ewout Kleinsmann Jul 24 '11 at 20:27
  • In your answer you've got echo $_GET['callback'] . '{' . "{'fullname' : 'Jeff Hansen'}" . '}'; But your response is indicating that you're using echo $_GET['callback'] . '(' . "{'fullname' : 'Jeff Hansen'}" . ')'; – Ewout Kleinsmann Jul 24 '11 at 20:36
  • Wow, didn't mean to upset you. This is the response of your jsonp.php: jQuery162012322438252158463_1311540946688({'fullname' : 'Jeff Hansen'}). The code you provided in your answer won't produce this. It would produce this: jQuery162012322438252158463_1311540946688{{'fullname' : 'Jeff Hansen'}} – Ewout Kleinsmann Jul 24 '11 at 20:58
  • 1
    You are right, I apologise. I had changed the code to curly braces but had not added the file to the server. Parenthesis works, curly braces doesn't. Answer updated. – Liam Bailey Jul 24 '11 at 21:04
19

More Suggestion

JavaScript:

$.ajax({
        url: "http://FullUrl",
        dataType: 'jsonp',
        success: function (data) {

            //Data from the server in the in the variable "data"
            //In the form of an array

        }

});

PHP CallBack:

<?php

$array = array(
     '0' => array('fullName' => 'Meni Samet', 'fullAdress' => 'New York, NY'),
     '1' => array('fullName' => 'Test 2', 'fullAdress' => 'Paris'),
);

if(isset ($_GET['callback']))
{
    header("Content-Type: application/json");

    echo $_GET['callback']."(".json_encode($array).")";

}
?>
Meni Samet
  • 343
  • 3
  • 5
8

To make the server respond with a valid JSONP array, wrap the JSON in brackets () and preprend the callback:

echo $_GET['callback']."([{'fullname' : 'Jeff Hansen'}])";

Using json_encode() will convert a native PHP array into JSON:

$array = array(
    'fullname' => 'Jeff Hansen',
    'address' => 'somewhere no.3'
);
echo $_GET['callback']."(".json_encode($array).")";
Alastair
  • 6,837
  • 4
  • 35
  • 29
mckoch
  • 330
  • 1
  • 4
  • The question was regarding [JSONP](http://en.wikipedia.org/wiki/JSONP) which requires the server's response to be wrapped with the client-callback and brackets e.g. `callback123([{a:1}])` – Alastair May 11 '13 at 14:00
2

Simple jQuery, PHP and JSONP example is below:

window.onload = function(){
 $.ajax({
  cache: false,
  url: "https://jsonplaceholder.typicode.com/users/2",
  dataType: 'jsonp',
  type: 'GET',
  success: function(data){
   console.log('data', data)
  },
  error: function(data){
   console.log(data);
  }
 });
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Mayur Shedage
  • 1,027
  • 2
  • 11
  • 19
0
$.ajax({

        type:     "GET",
        url: '<?php echo Base_url("user/your function");?>',
        data: {name: mail},
        dataType: "jsonp",
        jsonp: 'callback',
        jsonpCallback: 'chekEmailTaken',
        success: function(msg){
    }
});
return true;

In controller:

public function ajax_checkjp(){
$checkType = $_GET['name'];
echo $_GET['callback']. '(' . json_encode($result) . ');';  
}
Sal00m
  • 2,938
  • 3
  • 22
  • 33
0

Use this ..

    $str = rawurldecode($_SERVER['REQUEST_URI']);
    $arr = explode("{",$str);
    $arr1 = explode("}", $arr[1]);
    $jsS = '{'.$arr1[0].'}';
    $data = json_decode($jsS,true);

Now ..

use $data['elemname'] to access the values.

send jsonp request with JSON Object.

Request format :

$.ajax({
    method : 'POST',
    url : 'xxx.com',
    data : JSONDataObj, //Use JSON.stringfy before sending data
    dataType: 'jsonp',
    contentType: 'application/json; charset=utf-8',
    success : function(response){
      console.log(response);
    }
}) 
Atul Sharma
  • 9,397
  • 10
  • 38
  • 65