views:

58

answers:

2

Hi,

I've made on my website a search.php file that produce a JSON string, helping me to use real-time ajax for my apps.

But now, I'd like to open it as an API to others, but I discovered that $.get $.getJSON $.ajax doesn't allow to use my search.php file from other servers/domains.

How can I do to transform my php search into a search.json, exactly like Twitter, passing parameters to it.

Thx

A: 

Twitter uses two mechanisms to allow cross-domain access to the search.twitter.com domain: crossdomain.xml (for Flash) and JSONP (for JavaScript).

With JSONP, the calling JavaScript includes a callback=? parameter in the URL, where ? is the name of a callback function. The server-side script wraps the encoded JSON as:

?(<JSON here>)

This allows the query parameters to be encoded as the src URL of a script tag, allowing cross-domain access that XMLHttpRequest does not allow. When the data arrives, it is executed as a script. The JavaScript interpreter decodes the JSON since it is a valid subset of JavaScript and then calls the callback function with the decoded JSON as an argument. It shouldn't take more than a few lines of code to implement JSONP in your PHP script.

idealmachine
Thanx for your lights
CoBaLt2760
+1  A: 

getJSON is limited by your browser's security restrictions that lock down non-origin domains. In order to do cross-domain, you have to use JSONP, which requires you wrap the data in a function that is defined by the callback variable (e.g. $_GET['jsonp_callback']). e.g.

Search.php

<?php
    echo $_GET['jsonp_callback'] . '(' . json_encode($data). ');'
    // prints: jsonp123({"search" : "value", etc. });
?>

jQuery

$.ajax({
  dataType: 'jsonp',
  data: 'search=value',
  jsonp: 'jsonp_callback',
  url: 'http://yourserver.com/search.php',
  success: function () {
    // do stuff
  },
});

Just make sure that the callback variable that you define in your php script matches the jsonp value that you call through the .ajax query (or it defaults to "callback").

SideOfBacon
Thanx. That works perfectly , using jsonpCallback in your above code.
CoBaLt2760