views:

85

answers:

2

Hi,

I have to write a script which will be hosted on differents domains. This script has to get information from my server.

So, stackoverflow's user told me that i have to use JSON-P format, which, after research, is what i'm going to do. (the data provided in JSON-P is for displaying some information hosted on my server on other website)

  1. How do I output JSON-P from my server ? Is it the same as the json_encode function from PHP

  2. How do i design the tree pattern for the output JSON-P (you know, like : ({"name" : "foo", "id" : "xxxxx", "blog" : "http://xxxxxx.com"}); can I steal this from my XML output ? (http://bit.ly/9kzBDP)

  3. Each time a visitor browse a website on which my widget is it'll make a request on my server, requesting the JSON-P data to display on the client side. It'll increase dramatically the CPU load (1 visitor on the website who will have the script = 1 SQL request on my server to output data), so is there any way to 'caching' the JSON-P information output to refresh it only one or twice a day and stores it into a 'file' (in which extension?).

BUT on the other hand i would say that requesting the JSON-P data directly (without caching it) is a plus, because, websites which will integrates the script only want to display THEIR information and not the whole data. So, making a script with something like that:

jQuery.getJSON("http://www.something.com/json-p/outpout?filter=5&callback=?", function(data) {
................);
});

Where filter= the information the website wants to display.

  • Bonus question : do I have to use a JS framework to read JSON-P ? or JS pure without any framework to include on the page can do that ?

What do you think ?

Thank you very much ;)

+1  A: 

JSONP request

$.ajax({
  type: "get",
  dataType: "jsonp",
  url: "mothership.com/widget_data",
  data: {whatever: "here", requested_from: "someonesblog.com" },
  cache: true,
  success: function(data, textStatus, XMLHttpRequest){
    // respond to ajax call here

    // debug: make sure your data is getting loaded properly
    console.log(data);

    // do other necessary things here
  }
});

Encode and Output JSON from server

<?php
  header("Content-Type: application/json");

  # You can access data from the jQuery.ajax() call with $_GET here

  $data = array(
    "name" => "foo",
    "id"   => 1234,
    "blog" => $_GET["requested_from"]
  );
  echo $_GET["callback"] . "(" . json_encode($data). ");" ;

  # this will output something like
  # jsonp1255285823({"name":"foo","id":1234,"blog":"someonesblog.com"});

  exit;
?>
macek
thank you. I wonder what's the point in knowing who made the request ? (to allow certain domain and block others ?)
Tristan
@Tristan, I don't know what information you wanted available. The data I used is merely example data. Adjust this example to meet your requirements :)
macek
+2  A: 

You can use the json_encode function to get a JSON string representation of an object and then add the padding around it, ie:

$json = json_encode($myObj);
echo $callback . "(" . $json . ");";

Most JSON structures closely copy XML structures and naming conventions. Single nodes with no descendants become properties, repeated XML nodes would be JSON arrays and nodes with descendants are objects. See http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=396 for a decent, side-by-side view of data represented in both formats.

As for caching the data at the server, most caching methods can be a little overkill if your traffic isn't too heavy. See this answer to one of my own questions and this answer recommending memcached if you're still insistent that you need it. You can use the client cache control header expires to make sure the client fetches the data only once even across multiple pages/refreshes.

Bonus answer: the beauty of JSON-P is that you need no library whatsoever to parse it. The format is pure javascript and adding JSON-P to a page is as simple as adding a script to the page:

<script 
   type="text/javascript" 
   src="http://myurl.com/jsonp.php?callback=test&amp;filter=5"&gt;
</script>
Andy E
ok, THANKS. so without jquery it'll be like : document.write(x[i].getElementsByTagName('name')[0].childNodes[0].nodeValue);? (this one is for XML, but i've no idea how to parse a JSON-P format)
Tristan
@Tristran: JSON-P is parsed as a script by the browser. Your script sets up a function, e.g. `function myCallback(response) { ... }`, which is passed as the callback function to JSON-P. When the JSON-P is added to the document, your callback function is executed with the parsed JSON object as the first argument (in this example, `response`). All properties of the object are natively accessible via script, e.g. `var blog = response.blog;`.
Andy E
Without using jQuery you need to add a script element to the page which performs the request for you, parsing the response upon success: `var scrEl = document.createElement("script"); scrEl.src = "http://myurl.com/jsonp.php?callback=test"; document.getElementsByTagName("head")[0].appendChild(scrEl);`
Andy E
Tristan
i successfuly managed to work with JSON-P and jQuery, but i'm sorry but in PURE JS i can't get it.Could you please, be more specific, like macek did in his response ? thanks a lot !
Tristan