Breaking News
Loading...
July 16, 2015

Javascript cross-domain api for your website

2:30 PM
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
=')  == 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&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: 'http://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: 'http://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: 'http://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: 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:





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 + '
');
});
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.
Source URL: http://www.script-tutorials.com/javascript-cross-domain-api-for-your-website/

0 comments:

Post a Comment

 
Toggle Footer