What is transformRequest in angularjs - angularjs

I have a code
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
I know this code is change the serialization algorithm and post the data with the content-type, "application/x-www-form-urlencoded". But i dont know what is syntax of it . What is obj in function . Please explain for me . Thank

Transform Request is generally used for converting request data in the format which can be easily handled by server (Your Back end code).
For Example - If you want to send data with some modification in request then you can use it .
$scope.save = function() {
$http({
method: 'POST',
url: "/Api/PostStuff",
//IMPORTANT!!! You might think this should be set to 'multipart/form-data'
// but this is not true because when we are sending up files the request
// needs to include a 'boundary' parameter which identifies the boundary
// name between parts in this multi-part request and setting the Content-type
// manually will not set this boundary parameter. For whatever reason,
// setting the Content-type to 'undefined' will force the request to automatically
// populate the headers properly including the boundary parameter.
headers: { 'Content-Type': undefined},
//This method will allow us to change how the data is sent up to the server
// for which we'll need to encapsulate the model data in 'FormData'
transformRequest: function (data) {
var formData = new FormData();
//need to convert our json object to a string version of json otherwise
// the browser will do a 'toString()' on the object which will result
// in the value '[Object object]' on the server.
formData.append("model", angular.toJson(data.model));
//now add all of the assigned files
for (var i = 0; i < data.files; i++) {
//add each file to the form data and iteratively name them
formData.append("file" + i, data.files[i]);
}
return formData;
},
//Create an object that contains the model and files which will be transformed
// in the above transformRequest method
data: { model: $scope.model, files: $scope.files }
}).
success(function (data, status, headers, config) {
alert("success!");
}).
error(function (data, status, headers, config) {
alert("failed!");
});
};
};

Related

Multiple response types in a single $http call [duplicate]

I have an Angular 1.x application that is expecting to receive a binary file download (pdf) using a $http.post() call. The problem is, I'd like to alternatively get a processing error message that's sent as json. I can do this with the config
headers: {
'Accept': 'application/pdf, application/json'
}
The problem is I have have to set responseType: 'arraybuffer', otherwise the pdf binary is escaped (or altered such that it doesn't load). However, that prevents the json from being read or interpreted correctly.
How can I have both?
Edit: I'm going to try to clarify; perhaps my understanding is incorrect.
$http({
method: 'POST',
url: "/myresource",
headers: {
'Accept': 'application/pdf, application/json'
},
responseType: 'arraybuffer'
})
.then(
function(response) {
// handle pdf download via `new Blob([data])`
}, function(response) {
// pop up a message based on response.data
}
)
In a scenario where I return a pdf data block and a http status of 200, the first function handles the response and prompts the user to save the file. However if the status is an error (422), the response.data is undefined. I assume this is because the responseType is preventing the json from being handled correctly.
If I remove the responseType line, the error data is correctly read, but when the pdf is saved, some of the file bytes aren't correct and it's effectively corrupted. I assume this is because the file is being encoded because javascript was expecting a string.
An XHR responseType property can not be changed after a response has been loaded. But an arraybuffer can be decoded and parsed depending on Content-Type:
var config = {
responseType: "arraybuffer",
transformResponse: jsonBufferToObject,
};
function jsonBufferToObject (data, headersGetter, status) {
var type = headersGetter("Content-Type");
if (!type.startsWith("application/json")) {
return data;
};
var decoder = new TextDecoder("utf-8");
var domString = decoder.decode(data);
var json = JSON.parse(domString);
return json;
};
$http.get(url, config);
The above example sets the XHR to return an arraybuffer and uses a transformResponse function to detect Content-Type: application/json and convert it if necessary.
The DEMO on PLNKR

how to receive array data in ajax request page wordpress

I am sending array to PHP through angularJs $http, but when I receiving data it was showing null, I don't know is that my procedure is correct or not,
js file is
var newdisable_comments_on_post_types = JSON.stringify(allTabData.disable_comments_on_post_types);
$http({
method:'post',
url:url,
params:{
'disable_comments_on_post_types': newdisable_comments_on_post_types
}
});
while sending in the header it sending like this
disable_comments_on_post_types:{"post":false,"page":false,"attachment":false}
in the PHP file, i did some of the procedure to receive it
$a = $_POST['disable_comments_on_post_types']['post'];// method 1
$a = $_POST['disable_comments_on_post_types'] // method 2
$x=1
foreach($a as $val){
$b[$x]=$val;
$x++;
}
$a = $_POST['disable_comments_on_post_types']->post;// method 3
I am getting null in response every method while I returning data to check
echo json_encode($a);
am I doing any wrong or in WordPress we cant send an array to PHP?
Change Your $http service to this:
By default, the $http service will transform the outgoing request by
serializing the data as JSON and then posting it with the content-
type, "application/json"
$http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: allTabData.disable_comments_on_post_types
}).success(function () {});

Downloaded document getting corrupted using Blob method in angularJS

Downloading a file used to work fine in my application until I upgraded Angular to the latest. Even now, the file is getting downloaded, but the issue is that it is getting corrupted. Upload file is working fine and if we check in the file server, the file will be intact. But upon download, I am getting corrupted file.
Html :
<td data-title="''">
<a tooltip="Download CV" ng-hide="!talent.resumePath" tooltip-trigger tooltip-animation="false" tooltip-placement="bottom" ng-click="downloadResume(talent.id)" data-placement="top" data-toggle="tooltip" data-original-title="resume">
<img src="../../img/DownloadIcon.png" /></a>
</td>
Controller :
downloadResume: function(employeeId) {
return apiServices.getFileFromTalentPool('/talentpool/resume?id=' + employeeId)
},
Where, getFileFromTalentPool is : https://hastebin.com/yivaterozi.js
Endpoint :
public FileResult GetResume(int id) {
var result = _services.GetResume(id);
if (result != null) {
HttpContext.Response.ContentType = result.ContentType;
HttpContext.Response.Headers["Access-Control-Expose-Headers"] = "FileName";
HttpContext.Response.Headers["FileName"] = result.FileDownloadName;
}
return result;
}
Usually I download Doc files. I tried with a notepad file to see if it's the same. Strangely, I noticed that I am able to open the notepad file, but its content is manipulated to something like [object Object]. But for Doc files, it just shows:
How can I fix this?
it looks like the code at https://hastebin.com/yivaterozi.js was updated from using deprecated $http.success() method to current $http.then(). Promise' success callback function (within then method) receives only one object argument: https://docs.angularjs.org/api/ng/service/$http. Deprecated 'success' method got more arguments (data, status, headers) and data already contained raw data. When using then(), data is located under data property of response, so try to change your $http call to:
$http({
method: 'GET',
cache: false,
url: fileurl,
responseType:'arraybuffer',
headers: {
'Authorization': "Bearer " + $rootScope.userInfo.access_token,
'Access-Control-Allow-Origin': '*'
}
}).then(function (data) {
var octetStreamMime = 'application/octet-stream';
var success = false;
// Get the headers
var headers = data.headers();
...
...
please note that headers are fetched correct here from the data object and not from the third argument (just add var, since we removed empty arguments).
Now in each place that you use data, change it to data.data, like:
// Try using msSaveBlob if supported
var blob = new Blob([data.data], { type: contentType });
or just change argument data to response and add var data = response.data; anf modify headers getter to headers = response.headers();:
$http({
method: 'GET',
cache: false,
url: fileurl,
responseType:'arraybuffer',
headers: {
'Authorization': "Bearer " + $rootScope.userInfo.access_token,
'Access-Control-Allow-Origin': '*'
}
}).then(function (response) {
var octetStreamMime = 'application/octet-stream';
var success = false;
// Get data
var data = response.data;
// Get the headers
var headers = response.headers();
...
...

Send a zipped post request from angularjs using $http

I'm using $http on angularjs, and I have a fairly big request to send.
I'm wondering if there a way to do something like this:
content = "I'm a very long content string!"
$http.post content, url, 'gzip'
and have the post request content auto-gzipped and add an appropriate request header, so the server will know to unzip the content and pass it correctly to the controller
I can gzip the content on my side, and re-open it manually on the server, but I thought there should be some way to do it automatically. Is there?
See this post, like that you could give a parameter on the model so the server can decide if the content is a file and if the file should be unziped first
function Ctrl($scope, $http) {
//a simple model to bind to and send to the server
$scope.model = {
gzip: true,
file: true
};
//an array of files selected
$scope.files = [];
//listen for the file selected event
$scope.$on("fileSelected", function (event, args) {
$scope.$apply(function () {
//add the file object to the scope's files collection
$scope.files.push(args.file);
});
});
//the save method
$scope.save = function() {
$http({
method: 'POST',
url: "/Api/PostStuff",
//IMPORTANT!!! You might think this should be set to 'multipart/form-data'
// but this is not true because when we are sending up files the request
// needs to include a 'boundary' parameter which identifies the boundary
// name between parts in this multi-part request and setting the Content-type
// manually will not set this boundary parameter. For whatever reason,
// setting the Content-type to 'false' will force the request to automatically
// populate the headers properly including the boundary parameter.
headers: { 'Content-Type': false },
//This method will allow us to change how the data is sent up to the server
// for which we'll need to encapsulate the model data in 'FormData'
transformRequest: function (data) {
var formData = new FormData();
//need to convert our json object to a string version of json otherwise
// the browser will do a 'toString()' on the object which will result
// in the value '[Object object]' on the server.
formData.append("model", angular.toJson(data.model));
//now add all of the assigned files
for (var i = 0; i < data.files; i++) {
//add each file to the form data and iteratively name them
formData.append("file" + i, data.files[i]);
}
return formData;
},
//Create an object that contains the model and files which will be transformed
// in the above transformRequest method
data: { model: $scope.model, files: $scope.files }
}).
success(function (data, status, headers, config) {
alert("success!");
}).
error(function (data, status, headers, config) {
alert("failed!");
});
};
};

pyramid not work with angular $http post

$http({method: 'POST', url: 'http://localhost:5001/products', data: {token: $scope.product.token}}).success(
function () {
alert('success');
}
);
In the pyramid side, request.POST show that NOVars: Not a form request. Not an HTML form submission( Content-Type: application/json)
I am using cornice to provide my api(/products) and I thinks it is pyramid's problem.
Does anyone have a solution?
Angular sends the post body (data) as application/json while forms are normally sent as application/x-www-form-urlencoded. Pyramid parses the body and let you access it in request.POST when it's encoded as a normal form.
It is not be possible to represent every data encoded the Angular way (json) as a key/value pair like is provided by pyramid API.
[
1,
2,
3,
4
]
Solution on Pyramid side
It can be solved per view or globally
Per view
This is the pyramid way and the most flexible way to handle this.
#view_config(renderer='json')
def myview(request):
data = request.json_body
# deal with data.
return {
"success" : True
}
Globally
Pyramid can most likely be set to assume a body encoded as application/json is an object and its properties be put in request.POST.
Solution on Angular side
As with the pyramid side, it can be solved per request and globally.
Per request
You need to send the data the way forms are normally sent:
$http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj) {
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
}
return str.join("&");
},
data: xsrf
}).success(function () {});
Globally
To send posts as form by default, configure the $httpProvider to do so.
angular.module('httpPostAsForm', [])
.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$httpProvider.defaults.transformRequest.unshift(function (obj) {
var str = [];
for(var p in obj) {
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
}
return str.join("&");
});
}]);
Then include this module in your app:
angular.module("app", ["httpPostAsForm"]);
AngularJS $http.post is different from jquery's. The data you pass is not posted as a form but as json in the request body. So your pyramid view can not decode it as usual. You have to either:
directly access the request body and decode it in your pyramid view;
or modify your angularjs code to post your data as form content : see this other question in stackoverflow
the answer is angular $post do OPTIONS request first and then do the POST request, get data form the request.json_body
Use req.json_body if you post some json-decoded content. req.GET, req.POST, req.params only cope with from submissions. Btw, $http -> ngResource -> restangular ...
Try setting contenttype in $http, something like below.
$http(
{
url: url,
contentType: "application/json",
data: data,
method: method
})
.success(function (response) {
successcb(response);
}).error(function (data, status, headers, config) { errorcb(data); });
};
You can simply get the POST data this way:
query = json.loads(request.body)

Resources