Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

JQuery AJAX cross domain

Here are two pages, test.php and testserver.php.

test.php

<script src="scripts/jq.js" type="text/javascript"></script>
<script>
$(function() {
$.ajax({url:"testserver.php",
success:function() {
alert("Success");
},
error:function() {
alert("Error");
},
dataType:"json",
type:"get"
}
)})
</script>

testserver.php

<?php
$arr = array("element1",
"element2",
array("element31","element32"));
$arr['name'] = "response";
echo json_encode($arr);
?>

Now my problem: when both of these files are on the same server (either localhost or web server), it works and alert("Success") is called; If it is on different servers, meaning testserver.php on web server and test.php on localhost, its not working, and alert("Error") is executing. Even if the URL inside ajax is changed to domain.com/path/to/file/testserver.php
by

2 Answers

akshay1995
You can control this via HTTP header by adding Access-Control-Allow-Origin. Setting it to will accept cross-domain AJAX requests from any domain.

Using PHP it's really simple, just add the following line into the script that you want to have access outside from your domain:

header("Access-Control-Allow-Origin:
");

Don't forget to enable mod_headers module in httpd.conf.
kshitijrana14
it works, all you need:

PHP:
header('Access-Control-Allow-Origin: domain name');
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');

JS (jQuery ajax):
var getWBody = $.ajax({ cache: false,
url: URL,
dataType : 'json',
type: 'GET',
xhrFields: { withCredentials: true }
});

Login / Signup to Answer the Question.