1

I'm trying to send a JSON data to Server(Localhost to Hosting Site), unfortunately it does not work.

I have this code which I found on this site while searching for a solution and modified it a bit.

proto.html

This is the button to initiate the function

<button onclick="proto_test();">Test Button</button>

This is the code for the function that I'm having a problem with.

function proto_test() {
var data = {},
data['abc'] = [];
data['abc'].push('some info');
data['abc'].push('some more info');
json_data = JSON.stringify(data);

$.post("proto2.php", {'updateValues': json_data}, function(data) {
alert(data);
});

}

proto2.php

Here is the code for the php file which that I'm echoing it.

<?php
echo $_POST['updateValues'];
?>

This is what it looks like after you clicked the button. It alerts the result. (LOCALHOST TO LOCALHOST) In other words, I'm using XAMPP.

Result

Then if I changed the url to pass the data. Which I'm passing it to a SERVER (Hosting Site) It does not work.

$.post("http://www.mysite.com/proto2.php", {'updateValues': json_data}, function(data){
alert(data);
});

Any ideas how to fix this problem? I would be glad if someone helps me.

Thanks in advance.

Wesley Brian Lachenal
  • 4,381
  • 9
  • 48
  • 81

1 Answers1

4

Read the additional note in jQuery.post() API. AJAX requests are subject to the same origin policy. That's why you can't perform ajax post to different domain.

If you have control over the target server, you can enable cross-origin resource sharing. Check out this answer on how to enable CORS. Note: CORS is not supported in all browsers. See CORS browser support.

Community
  • 1
  • 1
Stanley
  • 5,057
  • 4
  • 34
  • 44
  • Thanks for the answer. I finished reading the documentation that you provided to me, thanks. Any suggestion for the alternative solution instead of using ajax? – Wesley Brian Lachenal Dec 18 '12 at 03:43
  • If you have control over the target server, you can [enable cross-origin resource sharing](http://enable-cors.org/). Check out [this answer](http://stackoverflow.com/a/7605119/1535679) on how to enable CORS. Note: CORS is not supported in all browsers. See [CORS browser support](http://enable-cors.org/client.html). – Stanley Dec 18 '12 at 03:52