1

Possible Duplicate:
JavaScript for detecting browser language preference

I tried using the following js code for detecting a users language, but each method results in undefined. My users use the system in two languages EN & FA.

Can I detect a users language by javascript or jQuery? If yes, how?

Demo: http://jsfiddle.net/AqXsp/1/

$('input').live('keyup', function(){
    alert(navigator.userLanguage); // Output this is "undefined"
    alert(navigator.systemLanguage); // Output this is "undefined"
    alert(navigator.browserLanguage); // Output this is "undefined"
})
Community
  • 1
  • 1
Kate Wintz
  • 633
  • 2
  • 11
  • 24

1 Answers1

6

The answer @Pekka pointed to is probably your best bet. It's actually an elegant solution, considering there is no such facility in JavaScript itself.

The author of the solution provides a very clear example:

var language;
$.ajax({ 
    url: "http://ajaxhttpheaders.appspot.com", 
    dataType: 'jsonp', 
    success: function(headers) {
        language = headers['Accept-Language'];
        nowDoSomethingWithIt(language);
    }
});

Of course, you could set language to some default value. And the result is an unparsed string, so there would need to be some more logic in nowDoSomethingWithIt().

Have a look at this working demo: http://jsfiddle.net/seYLA/

Community
  • 1
  • 1
  • 1
    This url: http://ajaxhttpheaders.appspot.com for my users have error "403. That’s an error. Your client does not have permission to get URL / from this server.You are accessing this page from a forbidden country. That’s all we know." How fix it? – Kate Wintz Dec 22 '11 at 12:40
  • I don't know what country you're in, but it's hosted on Google App Engine. Works fine here in the Netherlands. Anyway, if you've read the previously mentioned answer as you say you have, you know that it's just a Python script, which you can run on your own server if needed. So, again: read the previously mentioned answer: http://stackoverflow.com/a/3335420/990877 – Peter-Paul van Gemerden Dec 22 '11 at 12:44
  • Where is Python script for download and upload it in server? – Kate Wintz Dec 22 '11 at 13:06
  • Ehm... the code is in the answer. Right underneath *"Edit 2: As requested here is the code that is running on AppEngine"*. If you don't know how to run Python scripts on your server, or you don't have a server... This is not the place to ask for help. Extended discussions belong on a forum. – Peter-Paul van Gemerden Dec 22 '11 at 13:19
  • The simplw way is a short bit of javascript, as answered by Marco (2nd answer) on the 'duplicate' link, see link below `var userLang = navigator.language || navigator.userLanguage || navigator.browserLanguage || navigator.systemLanguage;` http://gu.illau.me/posts/the-problem-of-user-language-lists-in-javascript/ – Mousey Aug 15 '15 at 01:38