Javascript cross-domain api for your website

Tutorials

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

01 <?php
02 // set possibility to send response to any domain
03 header('Access-Control-Allow-Origin: *');
04 if (version_compare(phpversion(), '5.3.0''>=')  == 1)
05   error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
06 else
07   error_reporting(E_ALL & ~E_NOTICE);
08 // accept POST params
09 $sAction $_POST['action'];
10 $iParam1 = (int)$_POST['param1'];
11 $iParam2 = (int)$_POST['param2'];
12 // perform calculation
13 $iResult = 0;
14 switch ($sAction) {
15     case 'sum':
16         $iResult $iParam1 $iParam2;
17         break;
18     case 'sub':
19         $iResult $iParam1 $iParam2;
20         break;
21     case 'mul':
22         $iResult $iParam1 $iParam2;
23         break;
24     case 'div':
25         $iResult $iParam1 $iParam2;
26         break;
27 }
28 // prepare results array
29 $aResult array(
30     'result' => $iResult
31 );
32 // generate result
33 header('Content-type: application/json');
34 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

01 function do_sum(param1, param2, cfunction) {
02     // send ajax response to server
03     $.ajax({
04         type: 'POST',
06         crossDomain: true,
07         dataType: 'json',
08         data: 'action=sum&param1=' + param1 + '&param2=' + param2,
09         success: function(json) {
10             // and evoke client's function
11             cfunction(json);
12         }
13     });
14 }
15 function do_sub(param1, param2, cfunction) {
16     // send ajax response to server
17     $.ajax({
18         type: 'POST',
20         crossDomain: true,
21         dataType: 'json',
22         data: 'action=sub&param1=' + param1 + '&param2=' + param2,
23         success: function(json) {
24             // and evoke client's function
25             cfunction(json);
26         }
27     });
28 }
29 function do_mul(param1, param2, cfunction) {
30     // send ajax response to server
31     $.ajax({
32         type: 'POST',
34         crossDomain: true,
35         dataType: 'json',
36         data: 'action=mul&param1=' + param1 + '&param2=' + param2,
37         success: function(json) {
38             // and evoke client's function
39             cfunction(json);
40         }
41     });
42 }
43 function do_div(param1, param2, cfunction) {
44     // send ajax response to server
45     $.ajax({
46         type: 'POST',
48         crossDomain: true,
49         dataType: 'json',
50         data: 'action=div&param1=' + param1 + '&param2=' + param2,
51         success: function(json) {
52             // and evoke client's function
53             cfunction(json);
54         }
55     });
56 }

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:

01 <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
03 <script type="text/javascript">
04 $(document).ready(function() {
05     // execute method 1 (sum) by server
06     var param1 = 5;
07     var param2 = 10;
08     do_sum(param1, param2, function(data) {
09         $('#results').append(param1 + ' + ' + param2 + ' = ' + data.result + '<br />');
10         // execute method 2 (sub) by server
11         param1 = 25;
12         param2 = 15;
13         do_sub(param1, param2, function(data) {
14             $('#results').append(param1 + ' - ' + param2 + ' = ' + data.result + '<br />');
15             // execute method 3 (mul) by server
16             param1 = 8;
17             param2 = 5;
18             do_mul(param1, param2, function(data) {
19                 $('#results').append(param1 + ' * ' + param2 + ' = ' + data.result + '<br />');
20                 // execute method 4 (sub) by server
21                 param1 = 33;
22                 param2 = 11;
23                 do_sub(param1, param2, function(data) {
24                     $('#results').append(param1 + ' / ' + param2 + ' = ' + data.result + '<br />');
25                 });
26             });
27         });
28     });
29 });
30 </script>
31 <div id="results"></div>

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

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

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!

Rate article