Reputation: 3992
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.
Upvotes: 0
Views: 805
Reputation: 76784
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).
Upvotes: 1
Reputation: 7172
Sounds like you want to POST the information back to the rails application via Ajax.
Upvotes: 0