Q: How to play a song in jplayer using ajax json response in ruby on rails?

We have 2 functions play_song and songs. Play_song function is called when a user click on the clickable image of song in function call we pass audio_id as argument. This audio_id is sent to the controller which queries its database and retrieves information about the audio.

First Function :

function play_song(audio_id) {
            url:"<%=url_for :controller => 'controller_music',:action => 'action_find_music'%>",
            data:'audio_id=' + encodeURIComponent(audio_id),
            success:function (data) {
                var json1 = eval(data);
                songs(json1);  //call to the 2nd function to play song

In side controllers action query data base to retrieve URL of audio song and their related thumbnail as:- Suppose the Model name is Audio and id is its unique primary key and audio URL and thumbnail URL is place in attributes audio_url and thumbnail_url respectively in model Audio.

Inside controller : controller_music

def action_find_music
render :json => {:audio_url => @audio.audio_url, :name => @audio.thumbnail_url

Now, The second function is responsible for playing song in the jplayer.

Second Function :

    function songs(json1) {
        var audio_url_inside = json1.audio_url;
            ready:function (event) {
                $(this).jPlayer("setMedia", {
                }).jPlayer("play");   //attemp to play media
            swfPath:"<%= asset_path('Jplayer.swf')%>",

.Here in line no. 13 we used

  swfPath:"<%= asset_path('Jplayer.swf')%>",

which means this file is present locally in our sever and right now it is in public directory inside RAILS_ROOT so that it is easily accessible and used to play audio by jPlayer.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s