HI I am beginner in rails noe I am working with a music player application in rails 4 using jplayer and to create a play list I am using Ajax function
$.ajax({
type: 'GET',
url:"../albums.json",
success: function(data){
myPlaylist.add({title:$(this).attr("names")})
},
error: function(xhr,status,error){
alert(error);
}
});
what I want is to pass single album like albums/3.json to Ajax URL when I click the particular album to play ...any ideas will be welcome
Since you're a beginner, let me explain for you
Ajax
Ajax stands for Asynchronous Javascript And XML - it's designed to send requests in parallel to your standard HTTP requests. This basically means you're able to request data from the server without reloading the page.
The problem most people have is they think Ajax is this black magic trick; it's really just Javascript sending a request to your server on your behalf.
When you send a request with Ajax, you need to be able to send to the right data to the right URL, and then process the response accordingly.
I only learnt that a long time after I started with software, so I hope it helps.
--
Routes
#config/routes.rb
resources :albums #-> domain.com/albums/[:id]
The first step you need to take is to define your routes correctly. As Rails uses a resourceful routing structure (the routes are constructed around various controller-centric resources, you'll be able to use
When you send a request to albums/x.json
, you're really sending the request to the show
action of the albums
resource, which you'll need to have ready
--
Controller
When you set up your routes, you'll need to be able to handle the JSON request through your controller. You'll do this with the respond_to
block:
#app/controllers/articles_controller.rb
Class ArticlesController < ApplicationController
def show
@album = Album.find params[:id]
respond_to do |format|
format.html
format.json { render json: @album.to_json}
end
end
end
--
UJS
Finally, you'll be best using Rails' UJS for this - UJS is designed to send ajax
requests (amongst other things) without you having to write any JS code.
#app/views/controller/index.html.erb
<%= link_to "Play", @album, remote: true, format: :json %>
You'll then be able to capture the response using standard JS with some of the UJS ajax event hooks:
#app/assets/javascripts/application.js
$(document).on("ajax:complete", "#link", function(data){
//stuff here
});