Simple jQuery, PHP and JSONP example?

Jeff picture Jeff · Jul 24, 2011 · Viewed 110k times · Source

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?

Answer

Liam Bailey picture Liam Bailey · Jul 24, 2011

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