0

Jquery ajax cross domain

ajax cross domain

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>

output :
Capture

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.

DEMO

Ambar Hasbiyatmoko

Hello, I'm web developer. Passionate about programming, web server, and networking.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload the CAPTCHA.