Rails - why isn't ajax sending params to GET request - javascript

I am trying to send data through a get request using ajax but the param doesn't seem to be getting sent. I have a page that shows a random item from the db. You get to this page from a link in the navbar. Once on this page there is a link that allows you to skip the current item to find another random item making sure the next item isn't the one the user was just viewing.
routes.rb
get 'pending', to: 'items#pending'
view
<%= link_to 'Skip', '', class: "btn btn-default btn-xs",
id: "skip-btn",
:'data-item-id' => #pending_item.id %>
controller
def pending
#previous_pending_item_id = params[:id] || 0
#pending_items = Item.pending.where("items.id != ?", #previous_pending_item_id)
#pending_item = #pending_items.offset(rand #pending_items.count).first
respond_to do |format|
format.js
format.html
end
end
I have respond to both html and js because I am using the action for the navbar link as well as the link on the page. The link on the page is the skip button which should bring up another random item.
sitewide.js.erb
$('#skip-btn').on('click', function () {
$.ajax({
data: {id: $(this).data("item-id")},
url: "/pending"
});
});
When I look in the server log is says Started GET "/pending"... but doesn't make any mention of a param being sent. What am I missing?
The reason I'm using ajax for this is because I don't want the param showing in the url.
For clarification I need the url when visiting this page to always be /pending with no params or additional :id identified in the url. This page should always show a random record form the db. The only reason I need to send a param is to make sure no record is every repeated consecutively even though they are random.

I think you need to prevent default link action:
$('#skip-btn').on('click', function (event) {
event.preventDefault();
...
});

While you can do it the way you're attempting, I think it's worth pointing out that sending data in a GET request is a bit of an antipattern. So why not doing it the "correct" way!
Change your routes.rb to:
get 'pending/:id', to: 'items#pending'
and change sitewide.js.erb to:
$('#skip-btn').on('click', function () {
$.ajax({
url: "/pending/" + $(this).data("item-id")
});
});

I'd like you to check for the format its sending the the query to your controller. And the type of format you want to receive at the front end.
$('#skip-btn').on('click', function (e) {
e.preventDefault();
$.ajax({
dataType: 'json', //This will ensure we are receiving a specific formatted response
data: {id: $(this).data("item-id")},
url: "/pending"
});
});
In your controller maybe you want to pass it back as a json object.
def pending
##previous_pending_item_id = params[:id] || 0
#No need to make it an instance variable
previous_pending_item_id = params[:id] || 0
#Same goes for pending_items. No need to make it a instance variable, unless you're using it somewhere else.
pending_items = Item.pending.where("items.id != ?", previous_pending_item_id)
#pending_item = pending_items.offset(rand pending_items.count).first
respond_to do |format|
format.js
format.html
format.json { render json: #pending_item.as_json }
end
end
So that you can take value from response and append it to your page.
Similarly if you are expecting a js or html response back, you should mention that in your ajax call. Let me know if it does help you resolve your issue.
Update:
Let's say in your page, it shows the data of #pending_item object in a div,
<div id="pending_item">...</div>
When you're making a ajax request to your controller you want div#pending_item to show the a new random pending_item.
$('#skip-btn').on('click', function (e) {
e.preventDefault();
$.ajax({
dataType: 'html', //we'll receive a html partial from server
data: {id: $(this).data("item-id")},
url: "/pending",
success: function(res){
//We'll set the html of our div to the response html we got
$("#pending_item").html(res);
}
});
});
In your controller you do something like:
format.html { render partial: 'pending_item', layout: false }
And in your partial file "_pendint_item.html.erb" you'll access your instance variable #pending_item and display data
This will send the response to server as html, and there you'll only set your div's html to this.
Update 2
Your partial might look like this, or just however you want to display your pending item. The thing to know is it will be accessing the same instance variable #pending_item you have defined in your controller's method, unless you pass locals to it.
<div class="pending_item">
<h3><%= #pending_item.name %></h3>
<p><%= #pending_item.description %></p>
</div>
I suggest you do a console.log(res) in the success callback of your ajax call to see what you're getting back from server.

Related

RoR: send additional data on for submit with Jquery AJAX

I'm working on a rails form where I need to send an array created in Jquery to my rails controller. I've had a hard time getting the data in the proper format.
I managed to get the Jquery array to send through AJAX when doing an update of this model. It sends the normal PATCH and an additional PATCH for the array parameter. So 2 updates. Everything works find for updates, it's a bit hacky but does what I need it to.
This doesn't work on create though since I can't send two POST requests to create the same object? Does that make sense?
So I guess my question is how can I get my AJAX data to tag along with the normal form submit?
Here's
$('#employer_job_submit_button').on('click',function(){
$.ajax({
url:"/jobs/<%= #job.id %>",
type:'PATCH',
dataType:'json',
data:{
job: {
benefits: tags_array
}
}
});
});
Here's my view (part of it)
<%= form_for #job, :html => {:class => 'profile_form'} do |f| %>
.....
<div>
<%= f.submit "Post Job", class: "btn btn-primary btn-block", id: "employer_job_submit_button" %></div>
</div>
<% end %>
I tried separate code just for creating new jobs. Like this:
$('#employer_job_submit_button').on('click',function(e){
e.preventDefault();
var form_data = $('form').serialize()
$.ajax({
url:"/jobs",
type:'POST',
dataType:'json',
data:{
job: form_data
}
});
});
That sends all my form data through AJAX but I can't figure out how to add the "benefits" array to the form data. Also this is not really what I want to do because it bypasses the standard Rails form.
I just want to add my Jquery created array along with the form data.
That sends all my form data through AJAX but I can't figure out how to add the "benefits" array to the form data.
You may simply add the stringified array version to your data.
From:
dataType:'json',
data:{
job: form_data
}
To:
data: {
job: form_data,
benefits: JSON.stringify(tags_array)
}
In this way you will receive on your server two variables like in the following example:
job:firstname=Mickey&lastname=Mouse
benefits:["Saab","Volvo","BMW"]
Instead, if you want to continue to add to your serialized form data your array you can use jquery param like in the following:
var form_data = $('form').serialize() + '&' + $.param({"benefits": tags_array});
In this last way you need to decode the job parameter in your server side in order to extract the **benefits" array.

AJAX request Rails slideshow

I'm trying to send a JavaScript variable to my Rails controller through an AJAX request in order to use the variable to find the right instance of my model.
I can get my controller to print this variable, but I have not been able to save it anywhere such as a partial.
Here is my js.erb file:
$(".single-item").on('afterChange', function(event, slick, currentSlide, nextSlide){
$.ajax({
url: 'update_description',
type: 'post',
data: {slideNumber: $(".single-item").slick('slickCurrentSlide')},
dataType: 'json',
success: function(data) {
}
});
And my controller file:
def index
#posts = Post.all
if params[:slideNumber] == nil
#slideNumber ||= 0
else
#slideNumber = params[:slideNumber]
end
puts #slideNumber
respond_to do |format|
format.html {}
format.js {}
end
end
This puts #slideNumber in the controller correctly and prints the variable coming from JavaScript to console, however I am not able to pass it to a partial or to reuse it as a response from the JavaScript file. Am I missing something?
If you look at the server log, maybe you'll see that Rails is responding with the html content. Try adding .js to ajax request url so that Rails knows it should respond with js. For example:
var update_description = <%= "#{update_description_path}.js" %>

Can't get Ruby on Rails 4 Ajax working with Checkbox -Update Firing: but isn't changing checkbox or database

I'm attempting to use Ajax with Ruby on Rails 4 to watch when the checkbox changes and submit the form and save the checkbox change to the database. Even with the debugger I'm not seeing any errors. Any thoughts?
I recently changed the path to edit because I was getting a 404. I did this to it matches a route.
I just added the success function to the ajax call and it appears to be firing.
This is what I have currently:
This is product_controller
def update
if #product.update(safe_params)
redirect_to [:edit, #product], flash: { notice: t('shoppe.products.update_notice') }
else
render action: 'edit'
end
end
This is form in haml
= form_for product, :remote => true do |f|
= f.check_box :active
= f.label :active, t('shoppe.products.active'), :remote => true
This is js:
$('#product_active').bind('change', function() {
console.log('changed');
var action = $(this).parents('form').attr('action')+"/edit";
var method = "GET";
var checked = $(this).attr('checked');
var data = $(this).attr('value');
data ^= 1;
$.ajax({
method: method,
url: action,
data: checked,
success: function() {
alert("AJAX Fired");
}
})
debugger;
});
This is from rake routes
products GET /products(.:format) shoppe/products#index
POST /products(.:format) shoppe/products#create
new_product GET /products/new(.:format) shoppe/products#new
edit_product GET /products/:id/edit(.:format) shoppe/products#edit
product GET /products/:id(.:format) shoppe/products#show
PATCH /products/:id(.:format) shoppe/products#update
PUT /products/:id(.:format) shoppe/products#update
DELETE /products/:id(.:format)
UPDATE: I ended up putting a hidden submit button with the form and changing my js to and adding in a class to the form to allow me to hit all ajax with one set of code:
$('.ajax').bind('change', function() {
$(this).parents('form').submit();
});
You need to hit the update endpoint of your routes not the edit. The edit route is usually to load the edit view.
You'll also want to return a json encoded response in the update action and handle the success jquery callback and from there you would redirect in the client side or do whatever you want to do to update the UI. A redirect would be only useful from within your rails code if you were actually submitting a form and not doing ajax.

Rails: Send ActiveRecord received at ajax success as param to another ajax

Here's the situation: I have a view called "Dashboard" with a simple form and a "Draw Graphs" button. When I press this button I want to make two ajax requests that will return me the necessary data for my javascript to build two different graphs. The thing is that both requests will need to execute the exact same query on my database, and I want to avoid duplicating queries.
The way I'm currently doing this is by having my button fire a single ajax request that queries mysql for the necessary data, returning that data to my ajax success, and then passing that same data as params to two other ajax requests, which then use the data to generate the necessary structure for drawing the graphs.
It looks something like this:
Javascript:
$('#draw_graphs').click(function() {
$.ajax({
url: 'single_query',
dataType: 'json',
data: $('#myForm').serialize(),
method: 'get'
}).success(function(activeRecord) {
ajax_graph1(activeRecord);
ajax_graph2(activeRecord);
});
});
ajax_graph1 = function(activeRecord) {
$.ajax({
url: 'create_g1',
dataType: 'json',
data: {active_record: activeRecord},
method: 'post'
}).success(function(g1) {
create_g1(g1);
});
};
ajax_graph2 = function(activeRecord) {
$.ajax({
url: 'create_g2',
dataType: 'json',
data: {active_record: activeRecord},
method: 'post'
}).success(function(g2) {
create_g2(g2);
});
};
Rails:
def single_query
result = Data.where("etc... etc...")
respond_to do |format|
format.json { render json: result.to_json }
end
end
def create_g1
activerecord = params[:active_record]
graph1 = {}
activerecord.each do |ar|
#do whatever with graph1
end
respond_to do |format|
format.json { render json: graph1.to_json }
end
end
def create_g2
activerecord = params[:active_record]
graph2 = {}
activerecord.each do |ar|
#do whatever with graph2
end
respond_to do |format|
format.json { render json: graph1.to_json }
end
end
The problem I'm having is that apparently you can't simply send an active record from controller to javascript and back to controller again, the structure seems to get changed on the way. While single_query's result is of class ActiveRecord_Relation, when I pass it through the "javascript layer" it transforms into ActionController::Parameters class
Your reasoning makes sense: only want to hit the DB once. The issue is understanding how the "javascript layer" works with Rails. The AJAX call is getting an XHR Response object represented as JSON. This maps to a representation of your active_record in Rails but it's certainly not the same instance of an object in JS.
That being said, you should do what you need to do with the record on the Rails side and simply send the response to one AJAX call. In this case, have your $('#draw_graphs').click( AJAX call hit your controller in a corresponding def draw_graphs method. Have that method do the DB call, build each graph and pass both graphs back in a JSON hash (below). Then on the .success(function(graphs) parse the response and send the results to your 2 ajax_graph methods.
To build the JSON hash format.json { render json: { graph1.to_json, graph2.to_json } }
There are a few design optimizations here as well. You want to have a thin controller so consider only using the controller to sanitize/permit whatever params go into result = Data.where(...). Pass those params to a method in a class that does the query and maybe has a helper method to generate the graphs. It looks like you can even just do a case statement in that helper method based on which graph it is building because the create_g1 and create_g2 code looks similar. Likewise, you can refactor the code in the JS as well.

better way to do html updates then to expose javascript in rails3

I have a following code that is part of the _form.html.erb code. Basically I have a form in which I have a observe_field function where on change, it will set fields' values without refreshing the page. Following is my html code:
<script type="text/javascript">
// When DOM loads, init the page.
$(function() {
// Executes a callback detecting changes with a frequency of 1 second
$("#id_element_placeholder").observe_field(1, function( ) {
$.ajax({
type: "GET",
dataType: "json",
url: "/students/get/" + this.value,
success: function(data){
$('#last_name').attr('value', data.student.last_name);
$('#building').attr('value', data.student.building);
$('#room').attr('value', data.student.room);
}
});
});
});
</script>
Problem here is that I'm exposing lot of my code in javascript. Is there a better way to do it without exposing code in javascript?
Here is what my controller looks like:
def get
#student = Student.find(params[:id])
respond_to do |format|
format.html
format.json { render :json => #student }
end
end
Basically I get an id in a form and from there I have to get the corresponding object and update the fields on the page.
Assuming your design requires you to make AJAX calls to query student info by id, then you need to expose a URL for the call. If you don't want to expose a JSON data structure, you could return a chunk of HTML (instead of JSON), and replace the contents of the container of all of the controls you mention above.

Categories

Resources