AngularJS $http.post simple method is not working - javascript

I tried to use Angular $http.post(url, data) method. But I am facing some problems to post correct data to server (WebAPI). I have tried follwing options but none is working.
var data1 = new Object();
data1.UserName = "UserA1";
data1.Password = "password123";
data1.ConfirmPassword = "password123";
var data2 = angular.toJson(data1);
var data3 = JSON.stringify(data1);
var data4 = { UserName: "UserA2", Password: "password123", ConfirmPassword: "password123" };
var data5 = "UserName=UserA3&Password=password123&ConfirmPassword=password123";
$http.post(url, data1)
$http.post(url, data2)
$http.post(url, data3)
$http.post(url, data4)
$http.post(url, data5)
None is working. What kind of data is correct for this method. I tried JQuery.post() with above data and it works. Its super strange for me why this simple angularjs method so hard to use or I am missing something.
Update:
Basically I am working on following example. I want to register user from client side (/api/Account/Register).
http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api

This is because your server-side expects a request with its content x-www-form-urlencoded.
jQuery's $.post() sends the request with a Content-type of application/x-www-form-urlencoded whereas Angular's $http.post() sends the request with a Content-type of application/json (and also encodes the data as JSON (instad of form-data) if a JS Object is passed).
There are methods you can send x-www-form-urlencoded requests using $http (and there are several related answers on SO), but it involves less straight-forward code.
I suggest you change your server side to consume JSON requests.

Depending on what you have on server side, you should transform your request (that's the case for PHP, for example, or you can read from the input stream: php://input).
See this gist: https://gist.github.com/JensRantil/5713606.
If this is not solving your problem, please inspect the requests angular is creating (using the Developer Tools -> Network tab in Chrome for example), and tell us what you see.

Related

POSTing using ReactJS, Superagent and Python (flask)

I'm trying to post some data to a Python backend that i made with Flask. I'm using SuperAgent in a React component. For some reason i keep getting HTTP error 400.
I've read many posts about similar problems using JQuery and flask. The solution there is to set the contentType the same way i have and also JSON.stringify the data. I've tried stringify but it doesn't change anything. Still getting an HTTP 400.
Any ideas?
JS code:
request.post(link)
.set('Content-Type', 'application/json; charset=utf-8')
.send({tag: 'tag1', comment: 'Cool'})
.end(function(err, res){
console.log(res);
});
Python function/endpoint:
#app.route('/api/leavecomments', methods=['POST'])
def comment_to_photos():
comment = request.form['comment']
print(comment)
tag = request.form['tag']
...
So the issue for anybody else that has this problem, they need to use method named get_json which will have the values being passed to it in JSON format. In the case of the code above it was looking for those values as a query string post parameters, which is typically sent via form posts. In the case of an AJAX JSON post, the data exists inside the request.body.
For more information check out...
http://flask.pocoo.org/docs/0.10/api/#flask.Request.get_json

Reconciling WP API, AngularJS, and $resource/$http requests (getting X-WP-TotalPages)

I'm putting together an app using WP-API with an Angular frontend. I'm developing locally, with the data I'm trying to use loaded in from a remote server. Doing a $resource request for all posts works great.
But, I'm trying now to get the result of the X-WP-TotalPages header and can't figure out how to do it. Here's the code as it stands:
var request = function() {
var fullRoute = 'http://dylangattey.com/wp-json/posts/';
var defaultGet = {
method: 'GET',
transformResponse: function(data, headers){
response = {};
response.posts = JSON.parse(data);
response.headers = headers();
console.log(headers['X-WP-TotalPages']);
return response;
}
};
return $resource(fullRoute, {}, {
get: defaultGet,
query: defaultGet
});
};
// This gives me back the first 10 posts
request().query();
Chrome and curl both show that X-WP-TotalPages should be equal to 2 as a header. However, it just logs undefined.
Am I missing something? No matter whether I use $http or $resource I get the same result. I also have the same issue whether I use a remote site or a local WP installation on localhost. Really, I just want to know the total number of pages or even just the total number of posts for a given request, so if there's a better way to do it, I'd love to know.
You probably need to control the access to the specific headers you want on the server side.
See this thread for a brief discussion, or MDN on Access-Control-Expose-Headers.

POST data as json to a Servlet not working in Phantomjs

I am facing very strange issue here. I have a servlet running on my machine which renders my web page based on some input parameters.
Now, my screen capture with PhantomJS is not working if I try to send my data as a JSON object as a POST request type. For e.g. if I try:
Client side
var data = {"op": "get"};
page.open(address, 'POST', data, function (status) {
if (status !== 'success') {
console.log('[ERROR] :: Unable to fetch the address - ' + address + ", with data - " + data);
phantom.exit();
} else {
page.render(output);
}
console.log('processing...');
});
Server side
Now, on the server side, I am using Apache Velocity View templating so I have a single method which handles both get and post like :
public Template handleRequest(HttpServletRequest request, HttpServletResponse response,
Context context){
System.out.println(request.getParameter("op"));
//Always null
}
However, if I try sending my data from phantomjs as:
var data = "op=get&..."
It works
Also, at many places elsewhere in my code..I am doing Ajax POST requests to the same servlet and it works perfectly for all those request.
Would anybody explain why my servlet is not reading the JSON parameters passed from Phantomjs?
Servlets deal with simple request, so they only know how to parse (natively) HTTP parameters, either GET parameters from the URL, or POST parameters sent as application/x-www-form-urlencoded. Newer versions of the Servlet specification can also read multipart/form-data.
But there's nothing about JSON mentioned either in the Servlet or the HTTP specifications. So you must use a library that knows how to parse JSON and make the resulting object available in the Velocity context.

Sending JSON object back to server through YUI IO utility?

I am running a web page that generates random data and displays it in a HTML table. From the table I run a loop to gather the basic information (all rows that exist and exclude headers of table). This data gets stored in a JSON object called jData.
I want to send this data back to the server and store in a sqlite table named data. The way I am trying to do this is therough the YUI IO utility.
I am trying to wade the API documentation, but I am having no luck. I have two buttons on the page. One to generate the data and on to store the data. The store code is as follows:
var savedata = function(){
var tabledata = Y.one("#generatedtable")._node;
var jData = [];
var i = 1;
var length = tabledata.rows.length
while (i<length){
var samplerow = {};
var r = tabledata.rows[i];
samplerow.timestamp = r.cells[0].innerHTML;
samplerow.volts = r.cells[1].innerHTML;
samplerow.amps = r.cells[2].innerHTML;
samplerow.kW = r.cells[3].innerHTML;
samplerow.kWh = r.cells[4].innerHTML;
jData.push(samplerow);
i++;
}
Y.io("./savedata", Y.System_Config.postjData(jData));
};
Using the chrome debugger tools I see the array being stored properly into jData. I need some basic help with Y.io and how to make posts. Any basic help is much appreciated. My server is run bu the Django Python web application framework.
You should read the IO User Guide. Making a POST request with JSON data in YUI is as simple as setting the HTTP method to POST, adding the data and setting the Content-Type to application/json. The only caveat is that you need to turn the JSON object into a string first using JSON.stringify().
Y.io('/savedata', {
method: 'POST',
data: Y.JSON.stringify(jData),
headers: {
'Content-Type': 'application/json'
},
on: {
success: function (id, response) {
// do something with the response from the server, for example
Y.one('#some-node').set('text', response.responseText);
}
}
});
You can read more about all the configuration options for IO in the "Configuration Object" section of the User Guide. There is an example there of a POST request with JSON data.

AngularJS $http.put PUT Method not sending Data

I'm switching from jquery $.ajax, which was working fine, to using AngularJS $http.put to access a restful API.
I can make an API call, but the PUT data isn't getting sent - so my API sees a PUT request with an empty data object, which should contain a JSON string -> data.values = 'a json structure'
$http.put(
$rootScope.api_url,
{
values: jsonifiedValues
},
{
headers: {
apihash: sha256hash
}
}).success(function(data,status,headers,config){
// handle success
}).error(function(data,status,headers,config) {
// handle failure
});
I've not used AngularJS's $http before, but when I dump out the data in my PHP api it's just empty. this is how I'm pulling it from the request in the PHP:
parse_str(file_get_contents('php://input'), $put_vars);
$arr_req_data = $put_vars['values'];
In my API if the apihash sent from the request doesn't match the sha256 hash built on the PUT values, it fails.
This is working in JQuery, just failing now I've switched to $http. I'm not sure why the PUT data seems to be empty.
The return value from file_get_contents('php://input') will be a JSON string (provided everything got sent), so parse_str is not the right function to handle that data.
Instead use json_decode.
Also there is no need to send jsonified values, it will just make things more complicated as you'll have to use json_decode twice.

Categories