Reputation: 1740
I need to implement a cross-domain POST request. Using this code, everything worked fine in the same domain. But when I moved the backend to another domain - all stopped working! Therefore, there can be typos. There can be only where the error is related to the cross-domain request. I try send POST request using ajax and JSONP:
function requestToServer(url, success, myObjects)
{
$.ajax({
type: "POST",
crossDomain: true,
dataType: 'jsonp',
jsonp: 'jsonp_callback',
url: url,
data: "arrObjects=" + JSON.stringify(myObjects),
success: function(data)
{
success(data);
},
error: function()
{
alert('Server connection error!!!');
}
});
}
and server-script, where send data:
<?php
header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type');
include 'connection.php';
$arrObjects = json_decode($_POST['arrObjects']);
$title = $arrObjects->title;
$msg = $arrObjects->msg;
$lat = $arrObjects->lat;
$lon = $arrObjects->lon;
$query = "INSERT INTO `geo_markers` (`id`, `title`, `description`, `lat`, `lon`)
VALUES (NULL, '{$title}', '{$msg}', '{$lat}', '{$lon}')";
$res = mysqlQuery($query);
echo $_GET['jsonp_callback'].'({"success":true});';
mysql_close();
?>
but $_POST is empty. But $_GET takes values $_POST. If I check $_POST using var_dump, it is array(0), $_GET contains all send data!
What's wrong here? What went wrong can it be?
Upvotes: 1
Views: 1595
Reputation: 45124
You have send JSON formatted since you are using jsonp format. try json_encode before you echo
data.
Also keep in mind that when you make a cross domain jsonp call, JSONP isn't AJAX, it's merely a dynamic script element. You can't do a POST with a dynamic script element. There's no place to put the POST
data. So You will have to use GET
method.
Also keep in mind that you can use below format
$.getJSON(url + "?callback=?", null, function(data) {
});
Upvotes: 2
Reputation: 7141
JSONP doesn't work by POST request. JSONP works by the caller generating a script tag with a url which hopefully with generate a bit of script invoking a callback function with the data passed, as needed. if you want true cross domain posting, you'll have to implement Cross-Origin Resource Sharing (CORS) functionality with something to handle OPTIONS requests (maybe like with http://remysharp.com/2011/04/21/getting-cors-working/, but I confess, I didn't even fully scan it, I just looked over it to see that likely documents the basic, necessary functionality).
Upvotes: 3
Reputation: 97707
You cant make a jsonp POST request, jsonp can only be done with GET, which is why all the data is in $_GET.
Upvotes: 3