Codeigniter: Change languages on the fly (AJAX) - javascript

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);
}

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 );
}
});

Related

how to use key/value pairs in ajax call for jquery data option

Ive been checking out how to add variables to a ajax request which I can use in my server side script. I checked this stackoverflow post here and checked the jquery api docs here for a ajax request. I am getting error variable in my code is not defined.
I have this line in my code
return $.ajax({
type: 'GET',
url: '/users/show',
data: {'currentusershow': variable},
});
I was wanting it to do something like this with the results so I can keep all my different script in the one file.
if ($.get("currentusershow")) {
// do something here
}
else if...
i am not sure how to add the value to my code?
Also my url does not work going to the show.js.erb where my code is kept.
You need to declare and assign some value to the variable before the request.
Also you need to change the method type from GET to POST.
var variable = 'some data';
/*$.ajax({
type: 'POST',
url: '/users/show',
data: {currentusershow: variable},
success: function (response) {
// Do something with respsone
},
error: function () {
alert("error");
}
});*/
$.get( "/users/show", {currentusershow: variable} )
.done(function( response ) {
//do something with the response here.
});
Mamun was kind of right here as I did not explain myself very well in my question but I thought I would post this and clarify my question with what I was trying to do. The ajax call should be
return $.ajax({
type: 'GET',
url: '/users/show',
data: { currentusershow: 'variable'},
});
where the key is currentusershow and the value variable is a string and leave out defining the variable else where in the code. That way the url comes through correctly to the server being /users/show?currentusershow=variable. And in my destination file add my ruby code there to use the variables. In my question that code was more a php type code as I did not know what I was doing at the time.

jQuery AJAX reload specific div

I have the following code, as part of a code to add some value to a database.
After executing the $.ajax succesfully, I want a specific div (with class 'lijst') to be reloaded with the refreshed data.
$.ajax({
url: \"frontend/inc/functions/add_selectie.php\",
type: \"POST\",
data: ({ 'p_id' : p_id, 'v_id' : v_id, 'pd_id' : pd_id }),
cache: false,
success: function()
{
$(\".lijst\").hide().fadeIn('slow');
}
});
However, with this solution, only the div is refreshed, not the actual PHP variables that are specified in there. When I refresh my browser manually, the values are updated.
How can I refresh the div and also update the variables?
According to the jQuery.ajax documentation, the function signature of "success".
Type: Function( PlainObject data, String textStatus, jqXHR
jqXHR ) A function to be called if the request succeeds. The function
gets passed three arguments: The data returned from the server ...
So in other words:
success: function(data) {
$(".lijst").html(data).hide().fadeIn('slow');
}
Actually, the PHP variables specified in the html are worked at the sever part. PHP variables in the html have replaced by the string of there value when it is ready to be sent to the browser. And your ajax request will cause PHP to update database. So when you have sent the request and then refresh the page, PHP will replace the varables in the html again.
According to this above, your ajax request and the server repsonse are not aware of the PHP variables's existence. So you must update the content yourself.
Maybe you will do something like this:
success: function(data) {
$(".lijst").hide();
$(".title").html(data.title); // $(".title") may be a tag that surround a PHP variable
$(".content").html(data.content); // the same as $(".title")
$(".lijst").fadeIn('slow');
}

Before firing AJAX event, manipulate DOM -- CSRF Error

I'm working with Django, trying to make a chained AJAX call -- that is, a call that, when returned, kicks off more AJAX calls. I've been over the various methods of dealing with CSRF tokens and AJAX that the Django documentation provides, to no avail.
I have working code that allows for this chained AJAX call to successfully go through:
frm.submit(function(e){
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
headers: {'X-CSRFToken':csrftoken},
success: function(data, status){
$('#queue_div').append("<div class='container'>"+data['group_name']+"- "+data['client']+"<div id='queue"+counter+"'></div></div>");
var div_id = 'queue'+counter;
data['div_id'] = div_id;
var token = $.cookie('csrftoken');
data['csrf'] = token;
$('#'+div_id).html(data['status']);
callbackAJAX(data);
} //end success function
}); //end ajax function
e.preventDefault();
But when you delay the form event from firing the AJAX event right away, either by using "beforeSend" (as below):
var data = {'group_name':'name', 'client':'MrClient'}
var counter = 0
frm.submit(function(e){
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
headers: {'X-CSRFToken':csrftoken}
beforeSend:function(e){
$('#foo').append('<div class='container'>"+data['group_name']+"- "+data['client']+"<div id='queue"+counter+"'></div></div>');
} .....
or by adding an event right before the $.ajax call (as below):
frm.submit(function(e){
$('#foo').append('<div class='container'>"+data['group_name']+"- "+data['client']+"<div id='queue"+counter+"'></div></div>');
$.ajax({
type: frm.attr('method')....
You get a CSRF error.
I was successful in doing very, very simple functions such as the following:
var counter = 0;
frm.submit(function(e){
$.ajax({
type: frm.attr('method'),
sendBefore: function(e){
counter++;
}
But that's it. Anything more complicated gets rejected. I'm thoroughly confused as how to make heads or tails of what is actually happening OR what is acceptable to Django. & its CSRF protection.
The HTML you are trying to append is invalid. I believe that's why the form submission is not working. First you are trying to insert an element with ID foo into an element with the same ID ( foo ). Which is invalid HTML since IDs should never be repeated within the page.
Second and main problem is that you are appending <div id=foo></div> which should be <div id="foo"></div>

Get AJAX data from server before document ready (jQuery)

I want take some data from server and write it to global array in JavaScript. Then in document ready I want to use this array to create some new elements (options). I should have global array with this data, because after first load client can modify user interface using this data.
$(document).ready(function () {
UseAjaxQueryForFillGlobalArray();
MakingInterfaceUsingGlobalArray();
});
But I have strange behavior, when I debug page, I can see that method MakingInterfaceUsingGlobalArray working first, and just after I get data via AJAX with method UseAjaxQueryForFillGlobalArray and I don't have new interface(html options) with loaded data.
If I do like this:
UseAjaxQueryForFillGlobalArray();
$(document).ready(function () {
MakingInterfaceUsingGlobalArray();
});
Then in Firefox working fine, but in another web-browsers incorrect in first load (for example go to this page by link). But if I refreshing by F5, I have correct user interface which loaded via AJAX to global JS array.
How to fix it? Maybe I using totally incorrect way?
Added after comments:
This is my ajax function:
function UseAjaxQueryForFillGlobalArray(){
var curUserId = '<%= Master.CurrentUserDetails.Id %>';
var curLocale = '<%= Master.CurrentLocale %>';
$.ajax({
type: "POST",
url: "/segment.aspx/GetArrayForCF",
data: '{"userId":"' + curUserId + '","curLocale":"' + curLocale + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
//here is I doing parse my string from server and fill arrays.
}
});
}
I think that the problem is that you don't know exactly when the first function returns, since it'a asynchronous. So you should use the array in the callback only
function UseAjaxQueryForFillGlobalArray() {
// make the call
$.post(url, data, function() {
// let's be sure that the dom is ready
$(document).ready(function () {
// use the array
MakingInterfaceUsingGlobalArray();
}
}
}();// invoke the function
It's like reviving this post from the dead, but I had the same problem today, jQuery version greater than 1.6 has this ability:
https://api.jquery.com/jquery.holdready/
And I've used it like this:
$.holdReady(true);
var remoteJSONContent = null;
$.getJSON("http://www.example.com/remote.json", function(data) {
remoteJSONContent = data;
$.holdReady(false);
});
$(document).ready(function(){
console.log(remoteJSONContent);
});
Without using holdReady, I was getting null, after, I got the content.
For anyone still searching the answer for this.

How to initiate controller/action in CFWheels, for Ajax?

I have been trying to get cfwheels to work with FineUploader for two days now, and I just can't figure out how to force the jQuery script to execute a Controller/Action. This is how far I've come so far:
$(document).ready(function() {
var restricteduploader = new qq.FineUploader({
// Since we're using jQuery, use the jQuery way to select the HTML element
element: $('##restricted-fine-uploader')[0],
request: {
type: "POST",
url: $(this).attr("href") + "/index.cfm?controller=users&action=UploadFileXhr&format=json", // References "/say/hello?format=json"
dataType: "json",
endpoint: '/index.cfm?controller=users&action=UploadFileXhr&format=json'
},
multiple: false,
validation: {
allowedExtensions: ['jpeg', 'jpg', 'txt'],
sizeLimit: 5120000000 // 50 kB = 50 * 1024 bytes
},
text: {
uploadButton: 'Click or Drop'
},
showMessage: function(message) {
// Using Twitter Bootstrap's classes and jQuery selector and method
$('##restricted-fine-uploader').append('<div class="alert alert-error">' + message + '</div>');
},
debug: true
});
});
The CFWheels documentation says I have to use this to get an asynchronous request:
(function($){$(document).ready(function(){
// Listen to the "click" event of the "alert-button" link and make an AJAX request
$("#alert-button").click(function() {
$.ajax({
type: "POST",
url: $(this).attr("href") + "?format=json", // References "/say/hello?format=json"
dataType: "json",
success: function(response) {
$("h1").html(response.message);
$("p").html(response.time);
}
});
return false; // keeps the normal request from firing
});
});})(jQuery);
These three lines is what I'm trying to incorporate into my code (because that's what I think I need):
type: "POST",
url: $(this).attr("href") + "?format=json", // References "/say/hello?format=json"
dataType: "json",
But everything I've tried has not worked. I can't even work on my actual upload code to get that to work, since I can't even get the uploader to initiate the required controller/action.
Hopefully someone will be able to point me in the right direction. Thank you!
Question also posted to cfWheels mailing list: https://groups.google.com/forum/?fromgroups=#!topic/cfwheels/UKk_57y9ncQ
I'm not familiar with FineUploader, but normally when I am doing AJAX requests in Wheels, I use the urlFor() function to build the correct controller/action location.
CFWheels - urlFor
I think I know what problem you're facing. Follow these steps:
Make sure in your controller Say.cfc provides the JSON format to the Ajax call:
In the init() function of Say.cfc, make sure to add this:
<cffunction name="init" hint="It secures component from invalid access">
<!--- this is necessary --->
<cfset provides("json") />
</cffunction>
Now, in the hello action, render the data you want to provide without layout. Remove any <cfabort> tags present inside the action:
<!--- this will go at the very end of the action --->
<!--- here the attribute data is the data you want to serve: a query, struct or any other custom data generated inside a `<cfsavecontent>` --->
<cfset renderWith(data=data,layout=false) />
I hope this works for you.

Categories

Resources