Benjamin Oats Benjamin Oats - 1 month ago 14
Ajax Question

Ajax post function to external URL

I have a simple post function (see bellow)

$("#abi_test").click(function (event) {
$.post(
"get.php",
{
name: "Tom",
age: "30",
email: "johnsmith@gmail.com",
uniID: "3"
},
function (data) {
$('#stage').html(data);
}
);
});


how can i change this to post to
https://www.site.co.uk/some/get.php
?

I have tried

$("#abi_test").click(function (event) {
$.post(
"https://www.site.co.uk/some/get.php",
{
name: "Tom",
age: "30",
email: "johnsmith@gmail.com",
uniID: "3"
},
function (data) {
$('#stage').html(data);
}
);
});


But did not work

I am getting a error


XMLHttpRequest cannot load
https://www.site.co.uk/some/get.php. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://website.org.uk' is therefore
not allowed access.

Answer

You cannot do that. It's called cross-site scripting and it is not allowed by almost all servers. The only way around that is if you control the server you can respond with headers that allow requests from foreign URLs.

If you do control the server, then simply add this to the get.php file. You would be best off explicitly specifying the URL it's coming from though. Otherwise your server is vulnerable to a POST from any domain.

php header('Access-Control-Allow-Origin: *');