0

I'm having a little problem with my rails app. I am trying to pull a random name from an array and pass it into my rails controller and into a method.

This is my AJAX:

var artists = [array with some names]
randomA = {}

var randomArtist = artists[Math.floor(Math.random()*artists.length)];

randomA['a_name'] = randomArtist.toString();

$.ajax({
    url: "/songs_echowrap/" + randomA.a_name,
    dataType: "json"
    }).success(function(data) { 
        Do Stuff   
    }


    });  
});

Here is my routes:

get 'songs_echowrap/:artist_name' => 'users#get_echonest'

Here is my controller:

def get_echonest 

    foo = params[:artist_name]

    @rec = Echowrap.playlist_basic(:artist => params[:artist_name] , :results => 25)

    render json: @rec

end

The param is 'undefined' when i run a binding.pry in my terminal.

edrhuang
  • 121
  • 1
  • 2
  • 4
  • Have you tested this in the browser? Why do you get? Look in dev tools to see the request parameters. Raise the params hash in the controller action to see if the params do contain the artist name. – Mohamad Nov 19 '14 at 01:33
  • @Mohamad yes, I've done a console.log(randomA.a_name) and it does return a random artist's name which is what i want. But I don't think its reaching the controller correctly. In the terminal when I run a binding.pry, 'foo' is equal to "undefined" – edrhuang Nov 19 '14 at 01:57
  • Not `console.log()` Check the Rails request. Raise an error in the controller action and check dev tools to see the raised params hash in the request response. You will see exactly what `params` contains. Then you will no if this is your JavaScript or something else. – Mohamad Nov 19 '14 at 10:41

4 Answers4

1

Do like this in ajax,

$.ajax({
  type: "GET",
  url: "/songs_echowrap?artist_name=" + randomA.a_name,
  datavalue: 'html',
  }).success(function(data) { 
    Do Stuff 
  }
 });
});

In routes,

get 'songs_echowrap' => 'users#get_echonest'

In controller,

def get_echonest
  foo = params[:artist_name]
  @rec = Echowrap.playlist_basic(:artist => params[:artist_name] , :results => 25)
  render json: @rec
end
rick
  • 1,675
  • 3
  • 15
  • 28
0

Within your ajax call you should specify the method (in this case, looks like a GET) and the data required:

$.ajax({
  type: "GET", 
  url: "/songs_echowrap/" + randomA.a_name,
  data: randomA.a_name,
  }).success(function(data) { 
    Do Stuff   
}
});  
});
0

Try This: small change with your code, it will work add data varidable in your ajax call like this:

var artists = [array with some names]
randomA = {}

var randomArtist = artists[Math.floor(Math.random()*artists.length)];

randomA['a_name'] = randomArtist.toString();

$.ajax({
    url: "/songs_echowrap/" + randomA.a_name,
    dataType: "json",
    data: {artist_name: randomA.a_name }
    }).success(function(data) { 
        Do Stuff   
    }


    });  
});
Choco
  • 1,054
  • 1
  • 7
  • 20
0

Sorry, I am relatively new to Javascript and I should have been more clear with my code.

I realized that one of my variables was in the wrong scope so it kept returning as undefined. I was making two AJAX requests, and I thought i could return the value from the first and pass it through to the second. This question helped me understand my problem: How do I return the response from an asynchronous call?

this is my javascript now:

$('span').on('click', function(){
    $('#s_title').empty();
    $("#playlist_title").empty();
    $("#viito_list").empty();

    var p_title = $(this).html();
    $("#playlist_title").append(p_title);

    var id = $(this).data("id");
    var artistsList = []

    $.ajax({
        url: "/songs/"+id,
        dataType: "json",
        success: successCallback
    })

    function successCallback(data){
        for(var i = 0; i < data.length; i++){
                function msToTime(duration) {
                    var seconds = parseInt((duration/1000)%60),
                        minutes = parseInt((duration/(1000*60))%60)
                    minutes = (minutes < 10) ? "0" + minutes : minutes;
                    seconds = (seconds < 10) ? "0" + seconds : seconds;

                    return minutes + ":" + seconds ;
                }

            artistsList.push(data[i].artists[0].name);

            $("#s_title").append("<tr> <td>" + data[i].name + "</td>" + "<td>" + data[i].artists[0].name + "</td>" + "<td>" + msToTime(data[i].duration_ms) + "</td>" + "<td><span class='glyphicon glyphicon-remove song-select'></span>" + "</td> </tr>")
        }

        randomArtist = artistsList[Math.floor(Math.random()*artistsList.length)];
        getWeird(randomArtist)
    }


    function getWeird(rando){

        $.ajax({
        type: "GET",
        url: "/songs_echowrap?artist_name=" + rando,
        dataType: "json"
                }).success(function(data) {
                  $("viito_list").empty();

                  for(var i = 0; i < data.length; i++){

                    $("#viito_list").append("<tr> <td>" + data[i].title + "</td>" + "<td>" + data[i].artist_name + "</td> </tr>")
                  }


                });
    }


}); 
Community
  • 1
  • 1
edrhuang
  • 121
  • 1
  • 2
  • 4