Unpack data in PHP - javascript

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();

Related

put request in angular sends empty form data

I am trying to make a put request.
The api requires an array of numbers as request parameter
$http({
'requestpath/putrequesturl',
{
categories: [categorylist]
},
{
'method': 'PUT',
'authToken': authToken,
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
});
the data is sent as
requestpath/putrequesturl?categories=%5B5,19,12%5D
the query string parameter shows correct data, but Form Data in chrome dev tools is empty.
I tried this without content-type too, but it does not work
How can i make this request to send data as Form Data (Request body)
Edit: this is what api requires to get sent (if this is necessary):
Parameter: categories type:array
Your $http params looks a little odd. Maybe you are trying to do something like this..
$http({
method: "PUT",
uri: 'requestpath/putrequesturl',
headers: {
"Content-Type": "application/json",
"authToken": authToken // assuming this should be in the header
},
data: {
categories: [categorylist]
}
})
This is how the method put should seems
$http({
method: 'PUT',
url: uri,
headers: {"Content-Type": "application/json;charset=UTF-8"},
data: someData
});
or
$http.put(url, data, config)

Simple but struggling to convert POST request from using URL params to request body

I was making a POST request in the following manner, using URL params (which worked):
var PAYLOAD = `
<myxmlcontent>
<attribute name="id">1</attribute>
<attribute name="FullName">Joe Bloggs</attribute>
</myxmlcontent>
`
var URL = 'http://www.somewhere.com/integration?apiKey=company&apiToken=123&payload=' + PAYLOAD;
client.request({
url: URL,
type: 'POST',
contentType: 'application/xml'
}).then(
function(data) {
console.log(data);
}
);
But I wish to put the payload data into the request body.
Is this the correct way to do it? I am not sure, but my attempt has proved unsuccessful so far:
var PAYLOAD = `
<myxmlcontent>
<attribute name="id">1</attribute>
<attribute name="FullName">Joe Bloggs</attribute>
</myxmlcontent>
`
client.request({
url: 'http://www.somewhere.com/integration',
type: 'POST',
contentType: 'application/xml',
headers: {
apiKey: 'company',
apiToken: '123'
},
dataType: 'xml',
data: 'data=' + JSON.stringify(PAYLOAD)
}).then(
function(data) {
console.log(data);
}
);
I am currently building a client-side Zendesk app.
First you have to make sure the endpoint accepts data via POST, otherwise it will fail even if you are seding your data correctly, secondly, if you want to send data as an url-encoded form, you need to change the contentType to application/x-www-form-urlencoded and send the body as either an url-encoded string or by using the FormData object (if it's available in your framework), e.g.:
var myData = new FormData();
myData.append("payload", encodeURI(PAYLOAD));
client.request({
url: 'http://www.somewhere.com/integration',
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
headers: {
apiKey: 'company',
apiToken: '123'
},
dataType: 'xml',
data: myData
}).then(
function(data) {
console.log(data);
}
);
Don't forget to also encode the content of payload. In case your endpoint only accepts xml-encoded strings then you'd have to send the string as-is, just make sure to specify the correct contentType, in which case would be application/xml or text/xml.
SOLVED. This is what I had to do (thank you):
var PAYLOAD = `
<myxmlcontent>
<attribute name="id">1</attribute>
<attribute name="FullName">Joe Bloggs</attribute>
</myxmlcontent>
`
var URL = 'http://www.somewhere.com/integration';
client.request({
url: URL,
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
dataType: 'xml',
data: {
apiKey: 'company',
apiToken: '123',
payload: PAYLOAD
}
}).then(
function(data) {
console.log(data);
}
);
Helpful article: How are parameters sent in an HTTP POST request?

The posted data was populated into KEY not VALUE of req.body by 'body-parser'

I post data to node application from a cordova app using angular $http.
I tried several 'content-type', and only 'application/x-www-form-urlencoded' can be sent to the node server successfully, so my code is like:
$http({
url: CONSTANTS.login_url,
method: "POST",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: {"foo": "bar"},
})
But in the node application, the data I got from req.body is:
{"{"foo":"bar"}":""}
The key of the body is a String.
But my excepted result should be an Object like:
{
"foo": "bar",
}
There is a similar question in SO, the reason is that he uses 'JSON.stringify' in the frontend. But I don't use stringify why I can't get the excepted data?
Add a trnsformRequest function to transform the data to match the content-type
$http({
url: CONSTANTS.login_url,
method: 'POST',
url: url,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: {"foo": "bar"},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
}).success(function () {});
answer borrowed from here
hope this helps.

How do I get an AngularJS http post to a PHP file?

I'm trying to decipher how to get the json post from a JavaScript file to a PHP file.
This is my JS file:
var url2 = '/php/extractkeywords.php';
var jsonData = angular.toJson({
text: $scope.userTyping,
data: post
});
$http({
url: url2,
method: "POST",
data: "data=" + window.btoa($scope.textHTML),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data, status, headers, config) {
// Sending to extractkeywords.php
})
And this is my PHP file:
$data = json_decode(urldecode(base64_decode($_POST["data"])));
When I try to print $data, I don't get anything.
You need to pass JSON, here:
data: "data=" + window.btoa($scope.textHTML),
you are using the equals sign, which should not be used. JSON can have objects, arrays and key-value pairs, so you need a key. I believe this would improve your code:
data: {data: window.btoa($scope.textHTML)},

Using param and data in $http post in AngularJS

I am sending a JSON value as my data in my Angular $http POST request. I want to add another value to the data but I am not able to add it to the JSON. So I instead thought of adding it to the param attribute of the POST request. But I am not able to get the value as I expected in my server side which is the Servlet.
This is my $ http post:
$http({
method: 'POST',
url: 'edit',
params: oldValue,
data: message,
headers: {
'Content-Type': 'application/json'
}
}).then(function(response) {
console.log("Response in service" + response.data);
message.value = oldValue;
return response.data;
})
This is my Servlet:
String objectName = "";
objectName = request.getQueryString();
System.out.println("object name == "+ objectName);
I can actually get part of the data. But I am not able to get the whole data.
Any suggestions on alternate ways to accomplish this are welcome.
Try to pass additional data in data field only as you api method's parameter.
$http({
method: 'POST',
url: 'edit',
data: { parameter1 : mssage, parameter2 : oldValue }
headers: {
'Content-Type': 'application/json'
}
}).then(function(response) {
console.log("Response in service" + response.data);
message.value = oldValue;
return response.data;
})

Categories

Resources