Over a million developers have joined DZone.

Javascript: Cross-Domain API For Your Website

· Web Dev Zone

Javascript cross-domain api for your website

Welcome our readers. Today I would like to give a small but very important lesson where we will create our own cross-domain javascript api. I think that many of you have already tried to implement something similar, and maybe you faced with the impossibility of normal operation with the API functions at third-party domains. Basically, you just can not make a normal AJAX requests to a remote server and receive a reply in your javascript function. And all because of security regulations. But today I’ll show you how to solve this problem.

If you are ready – let’s start coding !


download in package

Step 1. PHP

As the first, we have to prepare our server side:

<?php

// set possibility to send response to any domain
header('Access-Control-Allow-Origin: *');

if (version_compare(phpversion(), '5.3.0', '>=')  == 1)
  error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
else
  error_reporting(E_ALL & ~E_NOTICE); 

// accept POST params
$sAction = $_POST['action'];
$iParam1 = (int)$_POST['param1'];
$iParam2 = (int)$_POST['param2'];

// perform calculation
$iResult = 0;
switch ($sAction) {
    case 'sum':
        $iResult = $iParam1 + $iParam2;
        break;
    case 'sub':
        $iResult = $iParam1 - $iParam2;
        break;
    case 'mul':
        $iResult = $iParam1 * $iParam2;
        break;
    case 'div':
        $iResult = $iParam1 / $iParam2;
        break;
}

// prepare results array
$aResult = array(
    'result' => $iResult
);

// generate result
header('Content-type: application/json');
echo json_encode($aResult);

You should pay attention to the first line of using custom header with ‘Access-Control-Allow-Origin’. It allows to send response to any server (mean – any domain). If you want to restrict it to use at the define domain – you can do it here. After – we do the simple actions, depending on $_POST action we perform different actions with received params. As the most easy example – I decided to implement the most simple math actions as summation, subtraction, multiplication and division. In the long run – we return our result in JSON format. Now, it’s time to prepare our server’s JS library:

Step 2. JavaScript

api.js

 

function do_sum(param1, param2, cfunction) {

    // send ajax response to server
    $.ajax({
        type: 'POST',
        url: 'http://www.script-tutorials.com/demos/301/api.php',
        crossDomain: true,
        dataType: 'json',
        data: 'action=sum¶m1=' + param1 + '¶m2=' + param2,
        success: function(json) {
            // and evoke client's function
            cfunction(json);
        }
    });
}

function do_sub(param1, param2, cfunction) {

    // send ajax response to server
    $.ajax({
        type: 'POST',
        url: 'http://www.script-tutorials.com/demos/301/api.php',
        crossDomain: true,
        dataType: 'json',
        data: 'action=sub¶m1=' + param1 + '¶m2=' + param2,
        success: function(json) {
            // and evoke client's function
            cfunction(json);
        }
    });
}

function do_mul(param1, param2, cfunction) {

    // send ajax response to server
    $.ajax({
        type: 'POST',
        url: 'http://www.script-tutorials.com/demos/301/api.php',
        crossDomain: true,
        dataType: 'json',
        data: 'action=mul¶m1=' + param1 + '¶m2=' + param2,
        success: function(json) {
            // and evoke client's function
            cfunction(json);
        }
    });
}

function do_div(param1, param2, cfunction) {

    // send ajax response to server
    $.ajax({
        type: 'POST',
        url: 'http://www.script-tutorials.com/demos/301/api.php',
        crossDomain: true,
        dataType: 'json',
        data: 'action=div¶m1=' + param1 + '¶m2=' + param2,
        success: function(json) {
            // and evoke client's function
            cfunction(json);
        }
    });
}

This is some kind of wrapper for our server side. I prepared 4 JavaScript functions for us: do_sum, do_sub, do_mul and do_div. Every function is for every our server’s function. Generally speaking, what we should to make proper requests: firstly, set the necessary URL of server’s api file (in our’s case it is: http://www.script-tutorials.com/demos/301/api.php), secondly, we should set ‘crossDomain’ to true, and finally – we should set dataType to ‘json’ (in case if we want to get json response). And finally, pay attention, that third param of every function is ‘cfunction’. This is any custom client’s function, and we should pass the server response to this function when we have got this response from our server.

Step 3. Usage (client side)

In order to use our API’s functions we can prepare an example:

<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="http://www.script-tutorials.com/demos/301/api.js"></script>

<script type="text/javascript">
$(document).ready(function() { 

    // execute method 1 (sum) by server
    var param1 = 5;
    var param2 = 10;
    do_sum(param1, param2, function(data) {
        $('#results').append(param1 + ' + ' + param2 + ' = ' + data.result + '<br />');

        // execute method 2 (sub) by server
        param1 = 25;
        param2 = 15;
        do_sub(param1, param2, function(data) {
            $('#results').append(param1 + ' - ' + param2 + ' = ' + data.result + '<br />');

            // execute method 3 (mul) by server
            param1 = 8;
            param2 = 5;
            do_mul(param1, param2, function(data) {
                $('#results').append(param1 + ' * ' + param2 + ' = ' + data.result + '<br />');

                // execute method 4 (sub) by server
                param1 = 33;
                param2 = 11;
                do_sub(param1, param2, function(data) {
                    $('#results').append(param1 + ' / ' + param2 + ' = ' + data.result + '<br />');
                });
            });

        });
    });
});
</script>

<div id="results"></div>

In this example we can see how I use javascript functions of our server. Look at the single example again

var param1 = 5;
var param2 = 10;
do_sum(param1, param2, function(data) {
    $('#results').append(param1 + ' * ' + param2 + ' = ' + data.result + '<br />');
});

We have just passed 3 params in our function: 2 digits and one function. We will receive the server’s response into this function. And, we can display this result somewhere (as example – we append it to #results element). I hope that everything is easy and understandable. Now you can copy our result’s example code into a new html document at your computer, and open it in your browser to see results.


download in archive

Conclusion

I hope that everything is clean in today’s code. If you have any suggestions about further ideas for articles – you are welcome to share them with us. Good luck in your work!

Topics:

Published at DZone with permission of Andrey Prikaznov, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}