a-ok Posted August 17, 2017 Share Posted August 17, 2017 Hi all! I'm using a language switcher on a site I'm building, and previously this has worked fine but as I am now using AJAX (and the language switcher is located in the head.inc file (which won't get called again while AJAX'ing between pages) I'm curious to know if anyone has implemented a multi-language switch on an AJAX-driven site. This is my simple switch. <ul class="languages"> <?php foreach ($languages as $language) : ?> <?php $url = $page->localUrl($language); ?> <li class="<?php if ($user->language->id == $language->id) : ?>is--active<?php endif; ?>"> <a href="<?php echo $url; ?>"><?php echo $language->title; ?></a> </li> <?php endforeach; ?> </ul> I had the same problem changing title tag/body classes as you switch between pages, so perhaps the solution is a similar one? <noscript data-title="<?php if ($page->id == 1) : ?><?php echo $pages->get("name=site-settings")->settings_site_title; ?><?php else : ?><?php echo $page->title; ?> – <?php echo $pages->get("name=site-settings")->settings_site_title; ?><?php endif; ?>"></noscript> <meta name="body-class" content="<?php echo $page->name; ?> <?php echo $page->template->name; ?>"/> Then, for example, when my AJAX is successful... var bodyClass = $('meta[name=body-class]').attr('content'), if (bodyClass !== undefined) document.body.className = bodyClass; Otherwise it just takes it server side from the head. Do you think I need to set up something similar for the language hrefs? Any thoughts are most welcome. Thanks! Link to comment Share on other sites More sharing options...
a-ok Posted August 18, 2017 Author Share Posted August 18, 2017 This is what I ended up doing... On each of my templates I added an include to languages.inc and in languages.inc I have the following... <?php $languages_array = array(); foreach ($languages as $language) { $url = $page->localUrl($language); $languages_array[] = array( 'url' => $url ); } $language_json = json_encode($languages_array, true); ?> <script> var languages = <?php echo $language_json; ?> </script> Then in my JS wrote a function that updates the values of the language switcher URL from the json outputted per page load. function languagesUpdate() { var language1Url = languages[0].url, language2Url = languages[1].url; $('aside.main ul.languages li').eq(0).find('a').attr('href', language1Url); $('aside.main ul.languages li').eq(1).find('a').attr('href', language2Url); } Then I called this function when the AJAX was successful and seems to work a treat. Maybe this'll help someone! 2 Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now