Reputation: 27
I am new to rails. I am trying to use ajax and call a controller method. The controller method creates an instance variable which I presume is available to success callback in ajax.
However, whenever I run the code, JS console gives "test_array is null" error. Please suggest a solution and an insight into what is happening. The code is as follows.
I have thoroughly researched this issue on internet (including SO) but none of the answers seem to be fitting my problem.
sentiscores_controller.rb
def render_phrase
@tag_cloud_temp = [{text: 'Hello', weight: 1000},{text: 'World!', weight: 1100}]
end
index.html.erb
$.ajax({
type: 'GET',
url: '/sentiscores/render_phrase',
data: {'senti_score': 5},
success: function(){
var test_array = <%= raw @tag_cloud_temp.to_json%>;
console.log(test_array[0]['text']);
},
error: function(exception){
console.log("Error! : "+exception);
}
})
The actual html source code looks like the following
$.ajax({
type: 'GET',
url: '/sentiscores/render_phrase',
data: {'senti_score': 5},
success: function(){
var test_array = null;
console.log(test_array[0]['text']);
},
error: function(exception){console.log("Error! : "+exception);}
})
Upvotes: 1
Views: 1321
Reputation: 1646
In your controller, you'll want to render
the JSON back to the AJAX call, like this:
# controller method
@tag_cloud_temp = [{text: 'Hello', weight: 1000},{text: 'World!', weight: 1100}]
render json: {
tag_cloud_temp: @tag_cloud_temp
}
Then, in your AJAX call, you'll want to recieve the data
from that render
, like this:
// in ajax call
success: function(data) {
console.log(data);
}
If you look at the data
object, you should see the information from your controller.
Upvotes: 5