Reputation: 7653
I am trying to work out how to change the languages on the fly using the Codeigniter Language System. So I made this ajax call which works but obviosly the values won't change until I reload the page unlease I somehow print out the values or set the variables in the function which is being called by AJAX ? What is the best way of doing this.
<script>
$(function(){
$('.lang-choices a').on('click' , function() {
var language = $(this).attr("data-lang");
$.ajax({
type: "POST",
url: js_site_url('langswitch/switchLanguage'),
data: "requestedLanguage=" + language,
cache: false,
success: function(html){
},
error:function(exception){alert('Exeption:'+exception);}
});
return false;
});
});
</script>
switchLanguage Function
public function switchLanguage()
{
$language = $this->input->post('requestedLanguage');
$this->session->set_userdata('site_lang', $language);
}
Upvotes: 0
Views: 1090
Reputation: 20554
Your question is a little bit unclear so the assumption I'm making is that you're flipping a backend flag that changes the output from the server. Using that assumption, here's what I'd recommend in order of magnitude:
In your success
handler, reload the page using window.location.reload(true)
. The true argument is essential since it makes a trip to the server to get new data. https://developer.mozilla.org/en-US/docs/Web/API/Location.reload
Your success handler seems to take html as an arg. I'm not sure if you're actually sending that based on your switchLanguage
function or if that's leftover from copy+paste somewhere. If you are indeed getting HTML data and it's page data, I'd use the context
option (http://api.jquery.com/jquery.ajax/) to filter down to the content of the document you're receiving then replace my page's content with this data
Here's an example of the latter:
$.ajax({
type: 'POST',
url: js_site_url( 'langswitch/switchLanguage' ),
data: 'requestedLanguage=' + language,
cache: false,
context: document.body,
success: function( html ){
// or similar
$( 'body' ).replaceWith( html );
},
error: function( exception ) {
alert( 'Exeption:' + exception );
}
});
Upvotes: 1