I am using angular js and php. I have an array to post in my controller from js file. I have converted my array to JSON and tried to pass the data like below
var update = {
method: 'POST',
url: apiPoint.url + 'up.php',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
params :{
alldatas: JSON.stringify($scope.alldata) ,
section : 'A',
}
By doing this I am getting 414 status error code. The url is too long. So I have tried JSONC to pack my data.. I use jsonc.min.js and have updated my code as below.
var update = {
method: 'POST',
url: apiPoint.url + 'up.php',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
params :{
alldatas: JSONC.pack($scope.alldata) ,
section :'A',
}
Now my data is passing through url and in my controller I get the data. But I can't unpack the data. Please help me to unpack the data.
I suppose you are using the standard $http
component, and the mentioned JavaScript object stands for its configuration object.
You should pass JSON data through POST, i.e. the request body, because the request URI length is limited. The params
option is serialized into GET. So you need to move your data (alldatas
) into data
option:
var req = {
method: 'POST',
url: apiPoint.url + 'up.php',
data: { alldatas: $scope.alldata },
// you might even stringify it
//data: JSON.stringify({ alldatas: $scope.alldata }),
headers: { 'Content-Type': 'application/json;charset=utf-8' },
params: { section : 'A' }
};
$http(req).then(function (response) {
console.log(response.data);
});
For the application/x-www-form-urlencoded
content type you should build a query string:
var req = {
method: 'POST',
url: apiPoint.url + 'up.php',
data: 'alldatas=' + encodeURIComponent(JSON.stringify($scope.alldata)),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
params: { section : 'A' }
};
The $_POST
superglobal is filled only for application/x-www-form-urlencoded
and multipart/form-data
content types. The other content types are available via the php://input
stream:
if (!empty($_POST)) {
$obj = $_POST;
} else {
$json = file_get_contents('php://input');
$obj = json_decode($json);
}
if ($obj) {
header('Content-Type: application/json');
echo json_encode($obj);
}
exit();