This tutorial is all about Cross Domain AJAX Request. We will learn how to do a Cross Domain AJAX Request with both GET and POST method by using simple JavaScript and PHP with cURL, file_get_contents and fopen.
Skills that you need for this tutorial are HTML, CSS, JavaScript, AJAX and PHP. At first, I’ll show you the regular method to make a cross domain AJAX call with get and post method. After that I’ll show you my own way to doing the same differently. I don’t know anybody already has done it in the second alternative way or not but yes, I did it myself for my own and I am sharing it with you. I’m using PHP to GET/POST data instead of JavaScript. Please keep on reading to see how it is done.
Files we need [File structure]
- Regular method (with CORS)
- GET method
- Files on Domain-A
- index.html
- script.js
- Files on Domain-B
- ajax.php
- Files on Domain-A
- POST method
- Files on Domain-A
- index.html
- script.js
- Files on Domain-B
- ajax.php
- Files on Domain-A
- GET method
- Special method (without CORS enabled – uing PHP)
- GET method
- Files on Domain-A
- index.html
- script.js
- ajax.php
- Files on Domain-B
- ajax.php
- Files on Domain-A
- POST method
- Files on Domain-A
- index.html
- script.js
- ajax-curl.php
- ajax-gfc.php
- ajax-fopen.php
- Files on Domain-B
- ajax.php
- Files on Domain-A
- GET method
- Download all files together – 70.7 KB (password is w3epic.com)
Suppose Domain-A is the place where you show the data and Domain-B is the place where the data is coming from.
1.1. [regular] Cross Domain AJAX Request with GET method
index.html [1.1.1. – Domain-A]
<html> <head> <title>Cross Domain AJAX Request - Regular GET Method [1.1.1. - Domain-A] - W3Epic.com</title> <script type="text/javascript" src="script.js"></script> </head> <body> <h1>Cross Domain AJAX Request - Regular GET Method [1.1.1. - Domain-A]</h1> <h2>by Arpan Das - <a href="http://w3epic.com">W3Epic.com</a></h2> <button id="load">AJAX load via Regular GET method</button><br /><br /> <div id="update"></div> </body> </html>
script.js [1.1.1. – Domain-A]
// Cross Domain AJAX Request - Regular GET Method [1.1.1. - Domain-A] - W3Epic.com window.onload = function () { document.getElementById("load").onclick = function () { var xhr; if (window.XMLHttpRequest) xhr = new XMLHttpRequest(); // all browsers except IE else xhr = new ActiveXObject("Microsoft.XMLHTTP"); // for IE var url = 'http://Domain-B/ajax.php?var=Hello World'; xhr.open('GET', url, false); xhr.onreadystatechange = function () { if (xhr.readyState===4 && xhr.status===200) { var div = document.getElementById('update'); div.innerHTML = xhr.responseText; } } xhr.send(); } }
ajax.php [1.1.2. – Domain-B]
<?php # Cross Domain AJAX Request - Regular GET Method [1.1.2. - Domain-B] - W3Epic.com header("access-control-allow-origin: http://Domain-A"); # GET method if (isset($_GET['var'])) { echo $_GET['var']; } else { echo "var is not set"; } ?>
—————————————————————————————————————–
1.2. [regular] Cross Domain AJAX Request with POST method
index.html [1.2.1. – Domain-A]
<html> <head> <title>Cross Domain AJAX Request - Regular POST Method [1.2.1. - Domain-A] - W3Epic.com</title> <script type="text/javascript" src="script.js"></script> </head> <body> <h1>Cross Domain AJAX Request - Regular POST Method [1.2.1. - Domain-A]</h1> <h2>by Arpan Das - <a href="http://w3epic.com">W3Epic.com</a></h2> <button id="load">AJAX load via Regular POST method</button><br /><br /> <div id="update"></div> </body> </html>
script.js [1.2.1. – Domain-A]
// Cross Domain AJAX Request - Regular POST Method [1.2.1. - Domain-A] - W3Epic.com window.onload = function () { document.getElementById("load").onclick = function () { var xhr; if (window.XMLHttpRequest) xhr = new XMLHttpRequest(); // all browsers except IE else xhr = new ActiveXObject("Microsoft.XMLHTTP"); // for IE var url = 'http://Domain-B/ajax.php'; xhr.open('POST', url, false); xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xhr.onreadystatechange = function () { if (xhr.readyState===4 && xhr.status===200) { var div = document.getElementById('update'); div.innerHTML = xhr.responseText; } } xhr.send('var=Hello World'); } }
ajax.php [1.2.2. – Domain-B]
<?php # Cross Domain AJAX Request - Regular POST Method [1.2.2. - Domain-B] - W3Epic.com header("access-control-allow-origin: http://Domain-A"); // # POST method if (isset($_POST['var'])) { echo $_POST['var']; } else { echo "var is not set"; } ?>
2.1. [special] Cross Domain AJAX Request with GET method
The main advantage of this php based special method over regular method is that, neither you need have access on Domain-B – nor Domain-B need to have CORS enabled. So, a cross domain AJAX call will be always successful even the ajax.php (here) is not being a public API.
index.html [2.1.1 – Domain-A]
<html> <head> <title>Cross Domain AJAX Request - Special GET Method [2.1.1. - Domain-A] - W3Epic.com</title> <script type="text/javascript" src="script.js"></script> </head> <body> <h1>Cross Domain AJAX Request - Special GET Method [2.1.1. - Domain-A]</h1> <h2>by Arpan Das - <a href"http://w3epic.com">W3Epic.com</a></h2> <button id="load">AJAX load via Special GET method</button><br /><br /> <div id="update"></div> </body> </html>
script.js [2.1.1 – Domain-A]
// Cross Domain AJAX Request - Special GET Method [2.1.1. - Domain-A] - W3Epic.com window.onload = function () { document.getElementById("load").onclick = function () { var xhr; if (window.XMLHttpRequest) xhr = new XMLHttpRequest(); // all browsers except IE else xhr = new ActiveXObject("Microsoft.XMLHTTP"); // for IE var url = 'ajax.php'; xhr.open('GET', url, false); xhr.onreadystatechange = function () { if (xhr.readyState===4 && xhr.status===200) { var div = document.getElementById('update'); div.innerHTML = xhr.responseText; } } xhr.send(); } }
ajax.php [2.1.1 – Domain-A]
<?php # Cross Domain AJAX Request - Special GET Method [2.1.1. - Domain-A] - W3Epic.com $url = 'http://Domain-B/ajax.php'; $fields = 'var=' . urlencode('Hello World'); $url = $url . '?' . $fields; echo @file_get_contents($url); ?>
ajax.php [2.1.2 – Domain-B]
<?php # Cross Domain AJAX Request - Special GET Method [2.1.2 - Domain-B] - W3Epic.com # GET method if (isset($_GET['var'])) { echo $_GET['var']; } else { echo "var is not set"; } ?>
2.2. [special] Cross Domain AJAX Request with POST method
This is the tricky part of this article. We’ll use PHP to post data instead of JavaScript. I’m showing you three ways to POST data using PHP and they are – 1. cURL, 2. file_get_contents and 3. fopen. Among three, cURL is highly recommended as cURL is fast, efficient and powerful. If your web host has cURL disabled, you still got two options remaining.
index.html [2.2.1 – Domain-A]
<html> <head> <title>Cross Domain AJAX Request - Special POST Method [2.2.1. - Domain-A] - W3Epic.com</title> <script type="text/javascript" src="script.js"></script> </head> <body> <h1>Cross Domain AJAX Request - Special POST Method [2.2.1. - Domain-A]</h1> <h2>by Arpan Das - <a href"http://w3epic.com">W3Epic.com</a></h2> <button id="load">AJAX load via Special POST method</button><br /><br /> <div id="update"></div> </body> </html>
script.js [2.2.1 – Domain-A]
// Cross Domain AJAX Request - Special POST Method [2.2.1. - Domain-A] - W3Epic.com window.onload = function () { document.getElementById("load").onclick = function () { var xhr; if (window.XMLHttpRequest) xhr = new XMLHttpRequest(); // all browsers except IE else xhr = new ActiveXObject("Microsoft.XMLHTTP"); // for IE // use any of three below [cURL method is highly recommended] var url = 'ajax-curl.php'; //var url = 'ajax-fgc.php'; //var url = 'ajax-fopen.php'; xhr.open('GET', url, false); xhr.onreadystatechange = function () { if (xhr.readyState===4 && xhr.status===200) { var div = document.getElementById('update'); div.innerHTML = xhr.responseText; } } xhr.send(); } }
ajax-curl.php [2.2.1 – Domain-A]
<?php # Cross Domain AJAX Request - Special POST Method [2.2.1. - Domain-A] - W3Epic.com # using cURL ---- @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ $url = 'http://Domain-B/ajax.php'; //open connection - initialize cURL handler $ch = curl_init(); //set fieds to be post $fields = "var=Hello World"; curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: application/x-www-form-urlencoded","Accept: */*")); curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); //execute post $result = curl_exec($ch); curl_close($ch); ?>
ajax-fgc.php [2.2.1 – Domain-A]
<?php # Cross Domain AJAX Request - Special POST Method [2.2.1. - Domain-A] - W3Epic.com # using file_get_contents ---- @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ $url = 'http://Domain-B/ajax.php'; $data = array('var' => 'Hello World'); // data to be send // use key 'http' even if you send the request to https://... $options = array( 'http' => array( 'header' => "Content-type: application/x-www-form-urlencoded\r\n", 'method' => 'POST', 'content' => http_build_query($data), ), ); $context = stream_context_create($options); $result = file_get_contents($url, false, $context); echo $result; ?>
ajax-fopen.php [2.2.1 – Domain-A]
<?php # Cross Domain AJAX Request - Special POST Method [2.2.1. - Domain-A] - W3Epic.com // # using fopen ---- @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ function do_post_request($url, $data, $optional_headers = null) { # credit: http://wezfurlong.org/blog/2006/nov/http-post-from-php-without-curl/ $params = array('http' => array('method' => 'POST', 'content' => $data)); if ($optional_headers !== null) $params['http']['header'] = $optional_headers; $ctx = stream_context_create($params); $fp = @fopen($url, 'rb', false, $ctx); if (!$fp) throw new Exception("Problem with $url, $php_errormsg"); $response = @stream_get_contents($fp); if ($response === false) throw new Exception("Problem reading data from $url, $php_errormsg"); return $response; } $url = 'http://Domain-B/ajax.php'; $data = "var=Hello World"; // data to be send $result = do_post_request($url, $data, $optional_headers = null); echo $result; ?>
ajax.php [2.2.2 – Domain-B]
<?php # Cross Domain AJAX Request - Special GET Method [2.2.2 - Domain-B] - W3Epic.com # POST method if (isset($_POST['var'])) { echo $_POST['var']; } else { echo "var is not set"; } ?>
I really enjoyed writing this article and hope this is useful for you.
If you have any problem, please comment below.
If you really like this article – please like, comment and share.
Thank you!
Thanks Arpan. You are the best. It really help me alot. I will share your article at my tweeter now. 😀
You’re welcome! 🙂
<3
Hi,
great tutorial Arpan. Only one question:
In the 2.2 Solution, if I want to send variables to the file ajax-curl.php, and then send them to ajax.php in Domain-B, how can I do it?
Thanks in advance.
Regards.
Noted, I’ll show that in another post.
Well written Arpan, thanks.
CORS is awesome! A much better than JSONP. See how to make Preflight requests or with credentials: https://zinoui.com/blog/cross-domain-ajax-request
posso usare l’italiano or english
Ok. I use translate and will be good ok?
i am from Italy hello. Can you help me translate? /rardor