Reputation: 10207
I have this Ajax function inside my application.js
file:
$("#project_person_id").change(function() {
$.ajax({
url: '/projects/get_invoice_types',
data: 'person_id=' + this.value,
dataType: 'script'
})
});
Is it possible to use a locale inside that function?
When I change line 3 to this:
url: '/de/projects/get_invoice_types',
I get the desired outcome (i. e. the output in German).
But of course I would like to set this dynamically. How can this be done?
Thanks for any help.
Upvotes: 3
Views: 1881
Reputation: 1
I solved this issue by adding data attributes to my erb template.
<button type="button" class="btn btn-success" id="save-job-position-btn" data-locale="<%= params[:locale] %>"><%= t("save") %></button>
$( "#save-job-position-btn" ).click(function() {
var locale = $(this).data("locale");
}
Upvotes: 0
Reputation: 2044
I solved this issue modifying $.get and $.post jQuery's functions.
I my case the locale is a parameter in the url, but it can be injected as Sagish did too
(function ($) {
var oPost = jQuery.post;
var oGet = jQuery.get;
jQuery.post=function(url , data , success , dataType ){
if (typeof data === "undefined") {
data={};
}
data=add_locale_to_url(data);
return oPost.apply(this,[url , data , success , dataType]);
}
jQuery.get=function(url , data , success , dataType ){
if (typeof data === "undefined") {
data={};
}
data=add_locale_to_url(data);
return oGet.apply(this,[url , data , success , dataType]);
}
})(jQuery);
And when I call $.get or $.post the locale is automatically added to the URL:
...
var remote_search=$.get("/expenses/search_users/"+$(this).val());
remote_search(function( data ) {
$("#processing").hide();
alert( "Usuari inexistent");
obj_error.val("");
});
...
Upvotes: 0
Reputation: 1065
you can set it dynamically wherever you like, i.e
var locale = "de"; // set it dynamically
and the use it as a global, like this
$("#project_person_id").change(function() {
$.ajax({
url: "/"+locale+'/projects/get_invoice_types', // use it
data: 'person_id=' + this.value,
dataType: 'script'
})
});
a more elegant why would be to set it as a data attribute to the body tag <body data-locale="de">
or to the HTML head <html lang="de">
, and pull it using a function
function locale() { return $("body").data("locale") }
or
function locale() { return $("html").attr("lang") }
and then retrieve it like this:
$("#project_person_id").change(function() {
$.ajax({
url: "/"+locale()+'/projects/get_invoice_types', // use it
data: 'person_id=' + this.value,
dataType: 'script'
})
});
there are other options of course, these seem straightforward.
Upvotes: 4