How to call rails create method for json response - ruby-on-rails

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] .

Related

Rails 6: AJAX data not reaching controller

I'm trying to make a pretty standard ajax call, this is my code:
// app/javascripts/packs/contacts.js
jQuery(() => {
$(".upload-contacts-button").on("click", (e) => {
e.preventDefault();
//...
$.ajax({
url: "/pre-parse-contacts",
type: "post",
data: { my_param: random_param },
success() {},
});
});
});
This is my route:
post 'pre-parse-contacts', to: 'contacts#pre_parse_contacts', as: 'pre_parse_contacts'
For some reason the data I send in the ajax request never reaches the controller, when I try to puts params in the controller action I get this result:
------- DEBUG --------
{"controller"=>"contacts", "action"=>"pre_parse_contacts"}
I'm sure the ajax call is made, even the js.erb view tries to render but I get errors due to I need the data I send in the ajax call. Why is this happening?
Sorry I found the answer to my issue, it seems I was trying to send an array of strings in the params of the ajax request, this is why it was never reaching the controller.
joining the array made the trick:
$.ajax({
url: "/pre-parse-contacts",
type: "post",
data: { my_param: random_param.join() },
success() {},
});

AngularJS sends nil parameters to API

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.

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.

Getting HTTP 405 Method not allowed error when calling Web API method from JQuery

I have the following method in my Web API controller
[HttpGet]
[ActionName("GetByModule")]
public Object Get([FromUri]int id)
{
//var dblayer = new Db(WebConfigurationManager.ConnectionStrings["ConnectionString"]);
var annDb = new ContactsDB(WebConfigurationManager.ConnectionStrings["ConnectionString"]);
return annDb.GetContacts(id).Tables[0];
}
Here i the Jquery code which i am using to call the method
$.ajax({
type: "GET",
contentType: "application/json",
url: link,
data: null,
dataType: "json",
success: function (data) {
alert(data.d);
},
error: function (jqXHR, textStatus, err) {
alert("Error");
}
});
The URL which is getting called is
http://localhost:56834/api/Contacts/GetByModule?id=9
But i keep getting HTTP 405 Method Not Allowed on calling it from Jquery.
Any idea what i may be doing wrong.
Thanks in Advance
Can you make sure you are making a "GET" request? (maybe from Fiddler or browser's debug mode). I say this because you seem to setting the "contentType" property in your jquery, which ideally should not be present as you should not be sending body in a "GET" request. Could you share your full raw request(may be from Fiddler)?

jQuery ajax GET fails

I have the following jQuery ajax request in a .js file:
$.ajax({
type: "GET",
url: "Download.aspx/ZipCheck",
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
function AjaxSucceeded(result) {
alert(result.d);
}
function AjaxFailed(result) {
alert(result.status + ' ' + result.statusText);
}
The request fails and an alert pops up that says "200 OK". However, if I change the ajax request type to "POST" then it works and I have an alert that pops up with the expected data being returned from Download.aspx/ZipCheck.
Why does the GET fail, and why does the POST succeed? My understanding must be flawed about the difference between the two, because I thought that a GET request still would return something from the server.
WebMethods are by default restricted to POST, you need to explicitly enable the GET request, for example using UseHttpGet on the ScriptAttribute, like this:
[WebMethod, ScriptMethod(UseHttpGet=true)]
public thing ZipCheck() {
//return object
}

Resources