Reputation: 364
I was wondering how you can get 2 variables to update a div tag using an ajax call instead of just 1. My current .js file:
$(document).ready(function() {
$("select").change(function() {
var selected_product_id;
selected_product_id = $(this).val();
$.ajax({
url: "/products/" + selected_product_id,
type: "GET",
success: function(data) {
$("#description").empty().append(data);
}
});
});
});
show.html.erb where i get the data:
<%= @product.item %>
I would like something like this
$.ajax({
url: "/products/" + selected_product_id,
type: "GET",
success: function(data) {
$("#description").empty().append(data[1]);
$("#price").empty().append(data[2]);
}
});
with
<%= @product.item %>
<%= @product.price %>
where my description div gets updated with @product.item and my price div gets updated with @product.price. How could I achieve this?
EDIT
updated .js file
$(document).ready(function() {
$("select").change(function() {
var selected_product_id;
selected_product_id = $(this).val();
$.ajax({
url: "/products/" + selected_product_id,
type: "json",
success: function(data) {
$("#description").empty().append(product.item);
$("#price").empty().append(product.price)
}
});
});
});
show.html.erb:
<%= @product.item %>
<%= @product.price %>
controller:
class ProductsController < ApplicationController
respond_to do |format|
format.html # show.html.erb
format.json { render :json => @product.to_json }
end
def index
end
def show
@product = Product.find(params[:id])
end
end
I'm pretty sure that controller isn't correct. I placed @product before respond_to and it didn't work so I just put respond_to without really knowing where it goes. Sorry for being such a noob. Thanks for all your help.
FINAL EDIT:
working javascript file:
$(document).ready(function() {
$("select").change(function() {
var selected_product_id;
selected_product_id = $(this).val();
$.getJSON("/products/"+selected_product_id,function(data){
$("#description").empty().append(data.item);
$("#price").empty().append(data.price);
});
});
});
Upvotes: 1
Views: 1184
Reputation: 54882
Ah, This remembers me a piece of code I wrote for you a week ago!
You can use JSON to render your Product:
#controller
def show
@product = Product.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render :json => @product.to_json }
end
end
And handle the response from the server like this:
$.ajax({
url: "/products/" + selected_product_id,
dataType: 'JSON',
success: function(data) {
var product = JSON.parse(data);
$("#description").empty().append(product.item);
$("#price").empty().append(product.price);
}
});
Edit #1: I found this method: jQuery.getJSON
: http://api.jquery.com/jQuery.getJSON/
Upvotes: 1
Reputation: 19040
You could use JSON, return
{"item": "<%=j @product.item %>", "price": <%= @produce.price %>}
then type: 'json'
in the ajax call
Upvotes: 1