How to add data to a Rails ajax request - ruby-on-rails

Is it possible to use data with Rails.ajax in a Rails 5.1+ (without jQuery) app while making a GET request? Or data work only with POSTs?
I have the following
Rails.ajax
url: "/pages?title=lorem}"
type: 'GET'
And I'd rather having
Rails.ajax
url: 'pages'
type: 'GET'
data: { title: 'lorem' }
But when I try my params look like { "object Object"=>nil, "controller"=>"pages", "action"=>"index"}
Adding dataType: 'json' nor dataType: 'text' seem to change the params passed to the controller.

It's possible to use data with a GET request; however, Rails.ajax simply appends the data to the url.
if options.type is 'GET' and options.data
if options.url.indexOf('?') < 0
options.url += '?' + options.data
else
options.url += '&' + options.data
Other than readability, there doesn't look to be an advantage in using the data option. Your first technique of appending the data to the url yourself is doing the same thing as Rails.ajax under the hood.
Rails.ajax
url: "/pages?title=lorem"
type: 'GET'
However, this is similar to how Rails.ajax handles data for POST requests as well. It doesn't perform any transformation on the data. The data is passed through untouched to the XMLHttpRequest. Data is sent like this with options.data passed through as-is.
xhr.send(options.data)

Related

Is it possible to use the same parameter scoping from form_for, except from an AJAX call?

I'm submitting some data to my rails backend via an AJAX call (axios specifically).
My AJAX request looks something like this:
Axios({
url: "/terms/" + event.target.term_id.value,
method: "put",
data: {
"term[en_text]": event.target["term[en_text]"].value,
"term[de_text]": event.target["term[de_text]"].value,
"term[jp_text]": event.target["term[jp_text]"].value
},
headers: {
"Authorization": token
}
}).then((result) => {
console.log(result)
})
It looks as though the backend doesn't do the same kind of scoping it would do if I had submitted this via form_for:
Parameters: {"term[en_text]"=>"Dates", "term[de_text]"=>"Datteln", "term[jp_text]"=>"foobars", "id"=>"1", "term"=>{}}
What the heck happened? As you can see from looking at the parameters received, none of them end up in "term" => {}
data: {
"term[en_text]": event.target["term[en_text]"].value,
"term[de_text]": event.target["term[de_text]"].value,
"term[jp_text]": event.target["term[jp_text]"].value
},
Would be correct if you are sending application/x-www-form-urlencoded or multipart/form-data as its a simple key/value format and rack parses parameters with brackets into hashes (and arrays) when parsing form data (or query strings).
However if you are passing application/json you need to pass an actual JSON object instead:
data: {
term: {
en_text: event.target["term[en_text]"].value,
de_text: event.target["term[de_text]"].value,
jp_text: event.target["term[jp_text]"].value
}
}
A JSON parser will not expand the keys, and there really is no need for that as JSON can actually express objects and arrays without the hackyness involved with form data.

Ajax response in erb from ruby method defined in controller

I have a ruby controller file with various methods defined, i want to get response of one of the method in erb i.e frontend using ajax call.
I am a beginner in ruby, so doesn't have much experience of handling requests in ruby, when i try to run the below code it gives error 404 in console stating url not found.
I have added relevant code snippets instead of entire code.
=> appcontroller.rb file
def returnimage_url
image_url = "http://dfdabfyag.jpg" //random url
{ :success => true, :img_value => image_url }.to_json
end
=> loadimage.erb file
<script>
function showImage(){
$.ajax({
url: '/returnimage_url',
method: 'GET',
dataType: "json",
success: function(response){
let image_data = JSON.parse(response);
console.log(image_data);
}
});
}
showImage();
</script>
You need to map the path /returnimage_url to your appcontroller.rb file and the specific method.
That should be done in your config/routes.rb file using something like this:
get 'returnimage_url', to: 'app#returnimage_url'
That will work if you rename your appcontroller.rb to app_controller.rb
See routing documentation for more info.
There are more issues in your code, but this should point you in the right direction and resolve the 404.

Rails 5: ajax post request not working correctly

I'm currently trying to add a form to my homepage. The survey calculates the needed impressions based on the user input.
The problem is that when I pass the value impressions for example 200 to ajax, it sends a POST request back to the form, but there I have #impressions = params[:impressions] which is nil.
Since #impressions = params[:impressions] already exists with the GET request. The POST request isn`t even showing up in the console.
Ajax code:
$.ajax({
data: 'impressions=' + impressions,
dataType: 'script',
type: 'POST',
url: "/pages/home"
});
Routes:
root to: 'pages#home'
post '/pages/home' => 'pages#home'
PagesController home:
protect_from_forgery :except => [:home]
def home
#impressions = params[:impressions]
end
What would be the right soultion? Probably I should set #impressions = 0 and change the ajax request from POST to PUT ?
Maybe format your Ajax request as Json?
$.ajax({
data: {impressions: impressions}
dataType: 'json',
type: 'POST',
url: "/pages/home"
});
Try below method.
$.ajax('/pages/home', {
type: "POST",
data: 'impressions=' + impressions,
dataType: 'script'
})
Hope this helps!!

Not getting form data sent via ajax post request 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.

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

Resources