Simple jQuery, PHP and JSONP example? Simple jQuery, PHP and JSONP example? ajax ajax

Simple jQuery, PHP and JSONP example?


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


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'}" . ')';


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).")";}?>