Not getting form data sent via ajax post request rails - ruby-on-rails

I am trying to send my form data which includes some text fields and one image field to controller via ajax post request.
The form data looks like this:
And this is the ajax call i am making
$.ajax({
type: "POST",
dataType: "json",
processData: false,
data: {'new_post_data': data},
url: "/posts/newpostcreate",
success: function(resp, status){
}
});
The request is being sent but in the controller I am getting something like
ActionController::Parameters {"object Object"=>nil, "controller"=>"posts", "action"=>"new_post_create"} permitted: false>
I have spent many hours looking for a solution and trying different solutions but still it does not work. I'm not getting what I am missing.

Looks like you are using the wrong format and that your 'data' variable is empty (hint given in the Params: "object Object"=>nil). Try passing this:
$.ajax({
type: "POST",
dataType: "json",
data: { new_post_data: "test" },
url: "/posts/newpostcreate",
success: function(response){
console.log(response);
}
});
Edit: I realized you have a file attachment in your data. I think your safest bet is to create a FormData object and assign all your data to it.
https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData
I am not sure about processData: false. I never used it.

Related

Rails sending duplicated/wrapped parameter

I create in my coffeescript code an object to pass via ajax post request which looks like this:
{"Category":[{"value1a":"v1a", "value2a":"v2a"}, {"value1b":"v1b", "value2b":"v2b"}]}
Via this code
$.ajax({
url: 'master/create',
type: "POST",
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(tickets)
})
tickets is the name of the object made.
but Rails is interpreting this like
Parameters:
{"Category"=>
[{"value1a"=>"v1a", "value2a"=>"v2a"}, {"value1b":"v1b", "value2b":"v2b"}],
"master"=>
{"Category"=>[{"value1a"=>"v1a", "value2a"=>"v2a"}, {"value1b":"v1b", "value2b":"v2b"}]
}
}
Where is this "master" coming from, and why is this happening?
If it helps, master is the name of the controller.

Rails 5: How Can a Form Submit with Custom HTTP Headers?

I cant seem to find any information on how to get a webform in Rails 5 to submit with custom headers. I would like the URL to which I am sending a PUT request to also receive some custom headers. I am surprised that there is no argument for form_for for this.
I could accomplish this by submitting the form to an action where I modify the headers there, e.g., request.headers['my-header'] = 'xyz'. I would then have to make the PUT request from within this "middle" controller action, and I feel this additional step is clunky and unconventional.
I could also use jQuery to bind to the submit click, and submit the form data after adding the headers via JavaScript. Id rather not involve another layer (i.e., JS) in this process.
I would rather not do either. Is there a way I can just use the Rails form helpers (or some controller helper) to add some custom headers to the request made by the form submission?
Rails does not have any tags that allows us to do that and therefore cannot add custom headers to your request.
In fact, you cannot set custom headers in html forms without xhr plugins,
You have to use it with ajax. Something like this:-
<%= form_tag("/your_url", method: :post, :remote => true, :html => { id: "form-id" }) do |f| %>
...your form here...
<% end %>
and then you ajax code:-
$('#form-id').submit(function() {
var valuesToSubmit = $(this).serialize();
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: valuesToSubmit,
headers: { 'Xmlrpc-Token': 'value' , 'Token': 'another_value'}
}).success(function(response){
//success code
});
return false;
});
Using only remote: true in rails will make ajax call, but you want to be able to customize it using the code above.
Browser will send only standard headers like cookies, contenttype, etc. You can not send Authorization header (or other custom) using HTML form submit. You should use AJAX to do that.
$("#idForm").submit(function(e) {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
<%= form_tag("/your_url", method: :post, :remote => true, :html => { id: "form-id" }) do |f| %>
...your form here...
<% end %>
$("#idForm").submit(function(e) {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});

Passing Backbone Model Attributes Using AJAX Request

I'd like to save my Backbone model attributes on the Rails side. My code looks like:
var model = this.model.toJSON(); //this.model is my Backbone model
$.ajax({
url: "/users/" + this.model.get('id'),
type: "PUT",
dataType: "json",
data: model
});
For some reason, the attributes are not being saved on the Rails side. I think my problem is: I'm not completely sure what to pass in as the "data" in the AJAX request (JSON, the actual object, etc)?
Thanks for any suggestions

Rails - update flash using an ajax post action

I have an action that calls a javascript file which contains an ajax method like this one:
$.ajax({
type: 'POST',
url: "<%= some_action(model) %>",
dataType: 'json',
data: { 'something': true },
success: function(received_data) {
// Do something with received_data
$('#notice').html("<%= escape_javascript(render 'layouts/flash_messages', flash: flash).html_safe %>");
}
});
The "some_action" tries to put some info into flash[:success], and I want to get it in the success function so that I can pass it to the render.
I have already tried the flash.now[:sucess], but nothing. It seems that it is only possible to do this if I write in the flash hash from the action that calls this javascript file - but I don't want this since "some_action" will generate dynamic content.
Is that something possible to to?
Thanks for the help!
you can send js request instead of json request .
and then in your "some_action.js.haml" file you can write
$('#notice').html("<%= escape_javascript(render 'layouts/flash_messages', flash: flash).html_safe %>");
what's happening here is that your javascript file is not getting refreshed hence content of html is not changing .

Which type of Ajax should I post to a Rails 3.1 controller when creating records?

I have a newsletter box that submits via ajax like this:
function ajax_subscribe(){
$.ajax({
url: '/subscribe',
type: 'post',
data: ({
email: $('#email').val()
}),
success: function(msg){
$('#newsletter_form').hide();
$('#newsletter .done').removeClass('hide');
}
});
}
As you can see I'm currently using type: 'post'
Will that go to the create function in my controller automatically?
This is a great article on the default Rails routes: Rails Routing from the Outside In.
The routes will be the same regardless of whether you're using ajax or synchronous calls.

Resources