In this tutorial, we will see ‘how to send request ajax from a server to another server’.
I have two server :
first server : http://demo.latcoding.com/
second server : http://ambar-hasbiyatmoko.com/
Ok, first server we used for request via ajax and second server for returning ajax.
In first server, we creating script like this :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script> $(document).ready(function(){ $('button').click(function(){ $('#send_process').html('sending data to ambar.hasbiyatmoko.com ..'); $.ajax({ method:"POST", url : "http://ambar-hasbiyatmoko.com/demo/ajax-crossdomain/index.php", data: {name: 'Luffy'}, success:function(response){ $('#send_process').html(response); }, error:function(er){ console.log(er); $('#send_process').html('Error'); } }); }); }); </script> <button>Send</button> <div id='send_process'></div>
In second server, we creating ‘php’ script :
header("Access-Control-Allow-Origin: *"); if(isset($_POST['name'])) { echo 'Accepted from http://ambar-hasbiyatmoko.com. <br>Your request name : '. $_POST['name']; }else { echo 'bad request'; }
Line 1, we must add header(“Access-Control-Allow-Origin: *”); when using ajax for cross domain.