0

I have this jQuery in my Rails app:

  $('#rankings_link a').click(function(){
    $.ajax({
      dataType: 'json',
      contentType: 'application/json',
      url: '/rankings',
      type: 'get'
    }).done(function(received_data){
      for (var m = 0; m < received_data.length; m++) {
        $('#rankings ol').append('<li>' + received_data[m] + '</li>');
      }
    });
  });

At the end of the rankings method in my controller is:

:render => 'json'

But when I click on the #rankings_link, it sends me to /rankings and displays a large block of preformatted text like this:

["Farag, Ali", "Harrity, Todd", ...]

I want to be able to put each element of (what seems to be) the array in an ordered list. But clearly this isn't what's happening and I don't know why.

Thoughts?

3 Answers 3

1

You need to stop the default action of <a> (which is to open the page specified by href attribute)

$('#rankings_link a').click(function(e){
  e.preventDefault(); // <- this
  // ...
});
Sign up to request clarification or add additional context in comments.

1 Comment

but if I do that, it won't render anything since I'm appending the data on a different page. i.e. I'm on the home page, click that link, and if I have peventDefault() in there, it won't go to the /rankings page...know what I mean?
0

Add :remote => true as the link param, also make sure you have in your application.js:

//= require jquery
//= require jquery_ujs

Comments

0

Try to validate your JSON before sending it to the view.

It is better if you can send some hard coded JSON first. The Online JSON Viwer validates JSON in a nice way.

You can can also create the JSON manually and render it as text, jQuery will return it as JSON.

There is the to_json method in ActiveSupport, you can try that also.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.