user3759722
user3759722

Reputation: 11

create callback API

New Restful API's like Google, OpenStreetview use a simple call back mechanism. Basically you call the API, adding a parameter &callback=my function. When executing a call to this API, as a result my function is called passing a JSON dataset.

I am trying to create the same mechanisme for a API I am building for my personal use.

As far as I understood my API needs to return a javascript, that calls the function that is passed in a script. For a test I created this:

    function apiCall(URL,values, keyPair,cBackPair) {
    // URL specifics URL to call
    // keyPair: <keyname>=<key>; leave black if unneeded
    // cBacPair: <callBackParametername>=<functionname>
    // called is: URL?values&keypair&cBackPair

    var request = (keyPair)?'&'+keyPair:'';
    request = URL + '?'+ encodeURI(values) + request + '&' + cBackPair;     
    var script = document.createElement("script");
    script.setAttribute("type", "text/javascript");
    script.setAttribute("src", request);
    document.body.appendChild(script);
 }

function callAPI() {
    apiCall('http://xllent.nl/map/ajax/answer.php','q=one','','s=doit');
}

function doit(result) {
    alert(result);
}

To test I call callAPI onload.

The script answer.php is very basic:

<?$s = $_GET['s'];
?>
<script type="text/javascript">
doit('jeroen');
</script>

Later the script would use $s to call the right script, and of course supply user data.

For now I am just trying to get the script doit('jeroen'); to be run. But nothing happens. Typing javascript:doit('jeroen'); in the browser window gives the result I would expect.

Any suggestions?

Upvotes: 0

Views: 157

Answers (1)

Evert
Evert

Reputation: 99515

Don't surround your javascript with <script> tags. You are not generating a HTML file with a javascript body.. You should think of this as if you're generating a javascript file on fly.

Javascript files also don't start and end with <script>

Upvotes: 2

Related Questions