DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Data Engineering
  3. Databases
  4. Javascript: Cross-Domain API For Your Website

Javascript: Cross-Domain API For Your Website

Andrey Prikaznov user avatar by
Andrey Prikaznov
·
Aug. 24, 12 · Interview
Like (0)
Save
Tweet
Share
6.26K Views

Join the DZone community and get the full member experience.

Join For Free

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!

API JavaScript

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

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • The Changing Face of ETL
  • Apache Kafka Introduction, Installation, and Implementation Using .NET Core 6
  • The Real Democratization of AI, and Why It Has to Be Closely Monitored
  • Implementing Infinite Scroll in jOOQ

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: