0

I have used ajax to get the object from controller.

  $('#city').on('change',function(){
    $.ajax({
      url: "/courses/index",
      type: "GET",
      data: {city: $('#city').val() },
      success: function(responseData) {
        alert(responseData);
      }
    });

So the responseData is the json format collection of the courses.

Currently, I have a html code: <%= @courses.first.name %>

How to modify the @courses instance which the result is the responseData of ajax.

Thanks.

2 Answers 2

1

You can't change the instance variable, because that belongs to the instance of the Ruby class you're using.

Using ajax invokes a new instance of your respective classes (on the server); javascript only works with the front-end view (HTML code / DOM), so you have to populate that with the response:

$(document).on('change', '#city', function(){
    $.ajax({
      url: "/courses/index",
      type: "GET",
      data: {city: $('#city').val() },
      success: function(responseData) {
        course = JSON.parse(responseData);
        $(".element").html(course.name);
      }
    });
});

Without knowing which data you're expecting back etc, it's kind of tough to know how to "parse" your data. However, the important thing to note is that you should not be trying to change the ERB, instead identify the html and replace it with the JSON you receive back.

Also, you'll need to use something like JSON.parse to create a workable object in your javascript (which you can then use to populate your page with).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for you explain.
0

Sounds like you want to POST the information back to the rails application via Ajax.

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.