haitruonginfotech haitruonginfotech - 3 months ago 11
Ajax Question

Error when using ajax from domain other

In host1 with domain http://domain1 I am using ajax with structure:


  1. index.php (that is include ajax)

  2. config.php (connect database)

  3. get_city.php



code here:

index.php
$(document).ready(function(){
$('.nation').change(function(){
var id = $(this).val();
var dataString = 'id='+id;
$.ajax({
type: 'POST',
url: '**http://domain1/get_data.php**',
data: dataString,
cache: false,
success: function(html) {
$('.city').html(html);
}
});
});
});


in get_city.php:

<?php
include 'config.php';
$id = $_POST['id'];
if($id) {
$query = mysql_query("Select * From jos_city Where nation_id = id");
while($row = mysql_fetch_array($query)) {
$id = $row['id'];
$name = $row['city_name'];
echo '<option value="'.$id.'">'.$name.'</option>';
}
}


When I use the other host with domain http://domain2, then ajax can't load

$(document).ready(function(){
$('.nation').change(function(){
var id = $(this).val();
var dataString = 'id='+id;
$.ajax({
type: 'POST',
url: '**http://domain1/get_data.php**',
data: dataString,
cache: false,
success: function(html) {
$('.city').html(html);
}
});
});
});


I think, the error occurs when calling the url: 'http://domain1/get_data.php' from domain1 to domain2. Has anybody got an idea, why this might happen?

Answer

AJAX calls must conform to same origin policy, you cannot make plain AJAX calls to another domain.

There are, however, workarounds:

To enable developers to, in a controlled manner, circumvent the Same Origin Policy, a number of 'hacks' such as using the Fragment Identifier, or the window.name property have been used to pass data between documents residing in different domains. With the HTML5 standard a method was formalized for this: the postMessage interface, which is only available on recent browsers. JSONP and Cross-Origin Resource Sharing can also be used to enable AJAX-like calls to other domains.[2]

For supporting older browsers, the JavaScript library easyXDM can be used to provide a unified API for the postMessage interface as well as a number of hacks used to allow Cross Domain Messaging (XDM).