AngularJS sends nil parameters to API - ruby-on-rails

I created a basic API with Ruby on Rails. Whenever I try to send data from a form in AngularJS, I get this message in the Rails Server:
Parameters: {"{\"content\":\"message\"}"=>nil}
So, it's creating null records in the DB.
This is the controller in AngularJS to send the data:
app.controller('postController', function($scope, $http) {
// create a blank object to handle form data.
$scope.message = {};
// calling submit function.
$scope.submitForm = function() {
$http({
method : 'POST',
url : 'http://localhost:3000/api/v1/messages',
data : $scope.message, //forms user object
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data) { ... }
});
};
});

You need to serialize the data when you send as x-www-form-urlencoded
Example copied from docs
.controller(function($http, $httpParamSerializerJQLike) {
//...
$http({
url: myUrl,
method: 'POST',
data: $httpParamSerializerJQLike(myData),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
});
Or use the defaults of $http which sends JSON in request body as application/json:
$http.post(myurl, data).then(...;

change this line:
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
to:
headers : {'Content-Type': 'application/json'}
Also encode to Json if it isnt like this:
data : angular.toJson($scope.message), //forms user object
This way you will send the correct JSON formatted data to API, make sure your API accepts Json encoded data just in case.

Related

Redirect from Rails controller after Angular POST

I have a normal Rails app (no SPA) and on one page only I'm using Angular.
At the end I'm sending a POST to the server with the form data (and it is working) and as the final step of the POST I'd like to redirect to another page.
Rails controller is like this:
def save
data = params[:data]
respond_to do |format|
format.js { render :js => "window.location.href = '/products';" }
end
end
But nothing is happening.
My Angular post is simple:
app.service('httpService', ['$http', function($http) {
this.post = function(data) {
$http({
method : 'POST',
url : '/cart/save',
data : { data: data },
headers : {'Content-Type': 'application/json'}
});
};
}]);
Calling service just like this, no promises:
this.save = function(ids) {
httpService.post(ids);
};
Any ideas? Thanks.
EDIT:
I have tried also change the mime-type to 'application/javascript', but no success:
app.service('httpService', ['$http', function($http) {
this.post = function(data) {
$http({
method : 'POST',
url : '/cart/save',
data : { data: data },
headers : {'Content-Type': 'application/javascript'}
});
};
}]);
Ok, so the problem was that the $http is sending an asynchronous request, thus the page cannot be redirected.
The solution was to send jQuery synchronous $.ajax(..., async: false);.

Parsing params that includes json string in rails controller

In a react-native app, I have the following post request that goes to a rails controller
fetch(POST_PAID_UP, {
method: 'POST',
body: JSON.stringify({
receipt_num: 127,
}).replace(/{|}/gi, "")
})
In the appropriate action of my rails controller I can examine params it looks like this;
{"\"receipt_num\":127"=>nil, "controller"=>"ios/accounts", "action"=>"create"}
so the data is being received. From params I need to extract the value of 'receipt_num'. I have tried JSON.parse(params), but I receive this error;
TypeError: no implicit conversion of Array into String
So how should I parse this data?
You need to add headers that indicate that the information being sent is of type json. So add the following hash to the fetch instruction;
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
You can then remove the .replace(/{|}/gi, "") which is just a work around to overcome the fact that you were not specifying the data was json. The final code should look like this:
fetch(POST_PAID_UP, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
receipt_num: transactionIdentifier,
})
})
You can find more information about fetch here

How to call rails create method for json response

What is the URL of JSON response if someone send the data on JSON using POST method. How can I store that data in my blog controller.
Create a proper routes and send that with the dataType 'Json' in ajax method. For example :-
function save_data(url, result){
$.ajax(url, {
type: 'PUT',
dataType: 'json',
data: {
store_data: result,
},
success: function() {
}
});
}
In this method you can pass url and data which you want to send in the method you are calling by url you can fetch that data in your controller by params[:store_data] .

sending array to mvc .net using $http post returning null

I have an MVC action that expects an array of int (int[] ids). I'm using $http post of angularjs but everytime I post it would return a null
$http({
method: 'POST',
url: url,
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8;' },
data: $.param({
pcode: $scope.pcode,
bId: $scope.bId,
brandIds: [898,55],
regId: $scope.regId,
__RequestVerificationToken: getVerificationToken() // this is Html.Antiforgery that the action needs for posts
})
}).success(function (result) {});
I tried this solution
AngularJs $http.post() does not send data
but it's throwing an injection error if i inject the $httpProvider. I'm using angularjs 1.3
$http({
method: 'POST',
url: url,
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8;' },
data: $.param({
pcode: $scope.pcode,
bId: $scope.bId,
brandIds: [898,55],
regId: $scope.regId,
__RequestVerificationToken: getVerificationToken() // this is Html.Antiforgery that the action needs for posts
},true)
}).success(function (result) {});
When you do not supply that parameter it will encode array brandids[]. You can see this in request.form. This is not working with mvc model binding.
If you supply that value then it encode array as brandids. This is what mvc model binder need so it will work.

Parameters vs JSON strings while designing an API with Rails for use with AngularJS

I am building an API to receive POST data and return JSON in Ruby on Rails 3. I am submitting the data using the angularjs $http object.
var post_data = {
content: $scope.post_content,
authentication_token: csrf
};
$http({
url: feed_endpoint,
method: "POST",
'Content-Type': 'application/json',
params: post_data
}).success(function(post_data, status, headers, config) {
}).error(function(post_data, status, headers, config) {
$scope.status = status;
});
}
The escaping of quotes etc. works well with this method where I was having issues with the JSON being created incorrectly while just passing a js data object(hash) to the $http.data object.
I am looking for input on the merits of doing it either way.
Thanks.
Try using $http.post, this form works for me.
$http.post(feed_endpoint, post_data, {"Authorization": ""})
.success(function(response) {...}

Resources