Javascript cross-domain api for your website

Javascript cross-domain api for your website

7 38040
Javascript cross-domain api for your website

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 !


Step 1. PHP

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

api.php

<?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: 'https://www.script-tutorials.com/demos/301/api.php',
        crossDomain: true,
        dataType: 'json',
        data: 'action=sum&param1=' + param1 + '&param2=' + 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: 'https://www.script-tutorials.com/demos/301/api.php',
        crossDomain: true,
        dataType: 'json',
        data: 'action=sub&param1=' + param1 + '&param2=' + 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: 'https://www.script-tutorials.com/demos/301/api.php',
        crossDomain: true,
        dataType: 'json',
        data: 'action=mul&param1=' + param1 + '&param2=' + 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: 'https://www.script-tutorials.com/demos/301/api.php',
        crossDomain: true,
        dataType: 'json',
        data: 'action=div&param1=' + param1 + '&param2=' + 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: https://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="https://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.

[sociallocker]

download in archive

[/sociallocker]


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!

SIMILAR ARTICLES

Polaroid gallery

0 23890

7 COMMENTS

  1. Nice Article. Would it be possible to use the same with iframes, for example load the results in an iframe assuming X-Frame- Options are set to DENY.
    Regards
    Maneesh

    • Hi Maneesh,
      It seems I haven’t understood you. As I know, iframe is a very closed system, basically we don’t have access to inner source of iframe. Usually it is restricted by browsers.

  2. Sir your effert is very nice And Very useful
    But i coding in C# So Sir Some problem facing understood in php code
    so sir some effert in c# I Heartly request to you
    Thx In advesed Sir

    • Hello Rajesh,
      Take my word, PHP is much more easy than C#. Even I was able to turn from C# to PHP easily (several years ago).

Leave a Reply