2

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

2 Answers 2

2

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").

Sign up to request clarification or add additional context in comments.

2 Comments

Thanx. That works perfectly , using jsonpCallback in your above code.
Hi there, I'm experiencing difficulties to re-use this piece of code inside a function, here : stackoverflow.com/questions/5263259/… any other great solution?
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.