I have created a new controller, that in future will be responsible only for translating strings for different objects. Here is the code of the controller:
# frozen_string_literal: true
class Api::TranslationsController < AuthenticatedController
def translate_string
@translated_string = GoogleTranslator.translate('hello', 'de')
render json: {translated_string: @translated_string.to_json}
end
helper_method :translate_string
private
def translations_params
params.permit(
:id,
:translated_string
)
end
end
It is placed in directory controllers/api/translations_controller. Here is the part of routes:
namespace :api do
resource :translations do
member do
get 'translate_string'
end
end
end
And here is part of my html.erb to call JS function:
<%= image_tag "google-icon.png", id: "google_icon", onclick: "test_transl()",
remote: true%>
And here is my JS code, currently only with Ajax:
<script>
function test_transl(){
$.ajax({
type: "GET",
url: "/api/translations/translate_string",
dataType: "json",
success:function (result){
console.log(result)
}
})
}
</script>
I expect this ajax code to translate the world 'hello' on German and get value @translated_string - 'hallo' in console but nothing happens except the fact, that the error I got is 'statusText: "parsererror"'. What may be wrong?
CodePudding user response:
I finally found what was wrong with my code. The problem was with fact that I didn't pass sessions token in ajax. So now my ajax code will look like this:
$.ajax({
type: "GET",
headers: {
"Authorization": "Bearer " window.sessionToken
},
url: "/api/translations/translate_string",
dataType: "json",
success: function(result){
console.log(result);
},
error: function (result){
console.log(result, this.error)
}
})
And def from controller like this:
def translate_string
@translated_string = GoogleTranslator.translate('hello', 'de')
render json: @translated_string.to_json
end
The output in console is: "hallo".