Brian Coolidge
Brian Coolidge

Reputation: 4649

Send JSON data to PHP SERVER (Localhost to Hosting Site)

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.

Upvotes: 1

Views: 2601

Answers (1)

Stanley
Stanley

Reputation: 5127

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.

Upvotes: 4

Related Questions