Why do these 2 alerts show different values? - javascript

I restart from begining.
My intranet webpage works like this:
1) User load the page, I load my motor database with $.Post in an array named motorsFull.
// load from my motor database
$.post("ajax.php?action=chargementBases",
function(data) {
motorsFull = data[0];
},"json");
// array built in ajax.php
$query = mysql_query("SELECT * FROM details_moteurs ORDER BY m_update_id DESC");
$i=0;
while ($infosMoteurs = mysql_fetch_assoc($query)) {
$arrayMoteur[$i] = $infosMoteurs;
$i++;
}
2) when user type in a research field I filter my array motorsFull and copy from it the lines matching the keywords with a function.
3) Every line of my motor database is an update, so you can have 3..10..25 entry for one motor id. This allow me to save all the change done by all users.
4) When a search is done, after filtering my motorsFull array I return the 10 first lines under motorsToDisplay array to my display update function.
5) To get the last value displayed on the user screen, for the 10 first motors returned I look for updates in my motorsFull array and update each cell of motorsToDisplay depending on some parameters with the following code. (All the code is not there only the update of the data for each different motor found).
for (var k=0; k < motorsFull.length;k++ )
{
//si on est sur le même moteur et que le n° d'update est différent
if(motorsToDisplay[i]['m_id'] == motorsFull[k]['m_id'] && motorsToDisplay[i]['m_update_id'] != motorsFull[k]['m_update_id']){
//historique k plus ancien que i
if(motorsFull[k]['m_last_update'] > motorsToDisplay[i]['m_last_update']){
// pour chaque case de la ligne en cours
for (var positionDansLigne in motorsToDisplay[i]){
//si la case récente est vide
if(motorsFull[i][positionDansLigne] == '')
{
// si la case ancienne n'est pas vide
if(motorsFull[k][positionDansLigne] == ''){
if(positionDansLigne != 'm_update_id' && positionDansLigne != 'm_user_done_update'&& positionDansLigne != 'm_update_type'&& positionDansLigne != 'm_update_comment'&& positionDansLigne != 'm_id'&& positionDansLigne != 'm_last_update'){
//on ecrase la valeur vide par l'ancien historique
motorsToDisplay[i][positionDansLigne] = motorsFull[k][positionDansLigne];
}
}
}
}
}
else{
//historique k plus récent que i
// pour chaque case de la ligne en cours
for (var positionDansLigne in motorsToDisplay[i]){
// si la case du tableau plus récent n'est pas vide
if(motorsToDisplay[k][positionDansLigne] != ''){
if(positionDansLigne != 'm_update_id' && positionDansLigne != 'm_user_done_update'&& positionDansLigne != 'm_update_type'&& positionDansLigne != 'm_update_comment'&& positionDansLigne != 'm_id'&& positionDansLigne != 'm_last_update'){
//on ecrase la valeur par le nouvel historique
motorsToDisplay[i][positionDansLigne] = motorsFull[k][positionDansLigne];
}
}
}
}
}
}
6) My problem start here. I dont know why but the first time I read my motorsFull everthing is okay, but after I readed it the data are updated like I done in my array motorsToDisplay with the function above. Nowhere in my code I update any value from motorsFull.
6b) I wrote following code to display you the content of my array motorsFull for a specific motor after and before it was read.
var textDebug ='';
for (var k=0; k < motorsFull.length;k++ )
{
if(motorsFull[k]['m_id']=='507'){
textDebug+='\r\r Line '+k+': ';
for (var y in motorsFull[k]){
textDebug+='['+ motorsFull[k][y]+'] ';
}
}
}
alert(textDebug);
7) If anyone could explain me why I dont read the same data twice from motorsFull, or why this array is updated it could help me. I can also provide the complete code but it is over 1000 lines :-)
Before
===================================================
After
Hint: If this line is commented my motorsFull dosen't change.
motorsToDisplay[i][positionDansLigne] = motorsFull[k][positionDansLigne];
EDIT: Here is my complete code (without ajax.php)
http://www.mediafire.com/view/dc48wv0voiqnuuw/fonctionsMoteurs.js
http://www.mediafire.com/view/j4uj4daztfyzai5/moteurs.php

I can't read the mediafire code (says "loading" indefinitely, and I've no idea whether I need an account or what else), but --
You have a non-trivial data structure (arrays of dictionaries), for which I did not see the initialization: I suspect that when populating motorsToDisplay and motorsToDisplay you at some time put the same dictionary into both.
Changing a dictionary by saying dict['key'] = value will change the dictionary, i.e., the change will of course change the dictionary, which when used two times, shows the change in two places.
Please check whether you can find a
motorsToDisplay[i] = motorsFull[k];
or a
dict = { ... };
motorsToDisplay[i] = dict;
motorsFull[k] = dict;
somewhere...

Related

Find an item and place it on my shopping cart

I'm learning both javascript and cypress, and I need your help, please... I want to find an item on a page, and add that item to the shoping cart.
I don't understand why I don't get any answer after .find. I don't get an error on cypress, but the item it's never added to the cart, and the cy.log dont display anyting.
/// <reference types="Cypress"/>
it ('ContarElementos', () => {
cy.visit ('https://www.saucedemo.com/v1/inventory.html')
cy.get('.inventory_list >')
cy.get('.inventory_list >').as ('ProductosPopulares')
cy.get('#ProductosPopulares').should('have.length', 6)
})
it ('Agregar elemento "top" al carrito de compra desde la pagina principal', function (){
cy.visit ('https://www.saucedemo.com/v1/inventory.html')
cy.get('.inventory_list >').as ('ProductosPopulares')
cy.get('#ProductosPopulares')
.find ('.inventory_item_name')
.each(($el,index,$list) => {
if($el.attr('.inventory_item_name') == 'Sauce Labs Onesie'){
cy.log ('Se encontró lo buscado')
cy.get ('#ProductosPopulares').eq(index).contains('ADD TO CART').click()
}
})
})
})
I know the place that has the item, so if I place it like this, it find appears on the cart, but I need it to work if I dont know the place on the list.
it ('Agregar elemento "top" al carrito de compra desde la pagina principal', function (){
cy.visit ('https://www.saucedemo.com/v1/inventory.html')
cy.get('.inventory_list >').as ('ProductosPopulares')
cy.get('#ProductosPopulares')
.find ('.inventory_item_name')
.each(($el,index,$list) => {
if($el.attr('.inventory_item_name') == 'Sauce Labs Onesie'){
cy.log ('Se encontró lo buscado')
}
})
cy.get ('#ProductosPopulares').eq(5).contains('ADD TO CART').click()
})
There is a mix-up between text and attribute, try swapping the .find() command and the .contains() command.
Something like this:
cy.contains('.inventory_list .inventory_item', 'Sauce Labs Onesie')
.find('button:contains("ADD TO CART")').click()

How to save whether a user clicked a button or not, and if so run a function

I have two functions translate_fr and translate_en, onClick when you click FR or EN the paragraphs are swapped either to english or french by grabbing their id's with inner.html
These two functions run on every html page, but obviously when refreshed or changing pages the onclick function reverts back to normal. So for instance if the user presses the FR button I want all the translate_fr functions on the other pages to run once the page loads, swapping the english paragraphs to french.
I need a way to store the users button click with local storage, and then a conditional statement saying if the user pressed EN run function translate_en else if FR then run function translate_fr.
Is this possible? I am VERY new to JavaScript and unfamiliar with local storage. I have no way how to do this. Here is the website on its domain lionkuts.ca for any other reference. I put two paragraphs as an example, though as you can see in the image I did this for every paragraph in the website.
function translate_en(){
document.getElementById("intro").innerHTML = `Here at Lion Kuts we are a cat only establishment that offers a full range of services from complete grooming, bathing to boarding. You and your pet will be thrilled to know that only professional, natural and biodegradeable products are used, any sensitivities or allergies will not be a problem.`;
}
function translate_fr(){
document.getElementById("intro").innerHTML = `Chez Coupe Lion, nous ne sommes qu'un chat établissement offrant une gamme complète de services du toilettage complet, de la baignade à l'embarquement.Vous et votre animal sera ravi de savoir que seul un professionnel, des produits naturels et biodégradables sont utilisés, tout les sensibilités ou les allergies ne seront pas un problème.`;
}
<div class="wrapper3">
<button class="translate" id="click1" type="button"onclick="translate_en()">EN
</button>
<button class="translate" id="click2"
type="button" onclick="translate_fr()">FR
</button>
</div>
<p id="intro">
Here at Lion Kuts we are a cat only
establishment that offers a full range of services
from complete grooming, bathing to boarding. You and
your pet will be thrilled to know that only professional,
natural and biodegradeable products are used, any
sensitivities or allergies will not be a problem.
</p>
You can use Window.localStorage to save the current language, and then use Window.onload to check the language.
Window.localStorage
Window.onload
function translate_en(){
Window.localStorage.setItem("language", "EN");
//translate the web page
} //translate_fr is same, but with french
Window.onload = (e) => {
let language = Window.localStorage.getItem("language");
if(language === "EN"){
translate_en();
} else if(language === "FR"){
translate_fr();
} else {
translate_en();//Default (if null)
}
}

i18n, javascript - is there a way to use a 2nd file for the differences?

I would like to use, as I am doing now, one file for my primary language and a second file for english.
This is working great.
Now I would like to add two more files. One with just the changes compared to the primary language and a second one for the other language.
In other word..the first file is a big file with all the dictionary but for a specific customer i need some words to be translated differently. Instead of writing another file 99% equal to the original I just would like to write the different words.
How can I do that?
this is my code:
var i18nextInstance = i18next
.use(i18nextXHRBackend)
.use(i18nextBrowserLanguageDetector)
.init(
{
detection: {
// Escludo localStorage. Praticamente ricorda l'ultima lingua usata.
//order: ['querystring', 'cookie', 'localStorage', 'navigator', 'htmlTag'],
order: ['querystring', 'cookie', 'navigator', 'htmlTag'],
},
fallbackLng: 'en',
lng: lingua_attiva,
debug: false,
ns: ['common'],
defaultNS: 'common',
backend: {
loadPath: './i18n/{{lng}}/{{ns}}.json',
crossDomain: true,
parse: function (data) {
// queste 3 righe sotto mi fanno utilizzare il json che include anche la lingua.
// infatti, nel caso di un file per lingua, la lingua non andrebbe messa. Solo che ci sono delle estensioni
// come quella di PHP che la vogliono lo stesso. Per questo la lascio e la escludo.
try {
var json = JSON.parse(data); // --> { en: { ... } }
var m = Object.keys(json); // --> ['en']
return json[m[0]]; // --> { common: { ... } }
} catch (e) {
alert(e); // error in the above string (in this case, yes)!
}
},
},
},
function (err, t) {
// initialized and ready to go!
// Se in ingresso non avevo passato nessuna lingua, la imposto adesso con quella rilevata
if (lingua_attiva == undefined) {
lingua_attiva = i18nextInstance.language.substr(0, 2);
}
// Se la lingua non è tra quelle abilitate, forzo inglese
if (lingua_attiva != 'it' && lingua_attiva != 'en') {
lingua_attiva = 'en';
}
ConfiguraMainWebsite();
AggiornaTraduzioni();
}
);
// Configuro le opzioni per utilizzare jquery nelle traduzioni
jqueryI18next.init(i18nextInstance, $, {
tName: 't', // --> appends $.t = i18next.t
i18nName: 'i18n', // --> appends $.i18n = i18next
handleName: 'localize', // --> appends $(selector).localize(opts);
selectorAttr: 'data-i18n', // selector for translating elements
targetAttr: 'i18n-target', // data-() attribute to grab target element to translate (if diffrent then itself)
optionsAttr: 'i18n-options', // data-() attribute that contains options, will load/set if useOptionsAttr = true
useOptionsAttr: true, // see optionsAttr
parseDefaultValueFromContent: true, // parses default values from content ele.val or ele.text
});
You can create a new file with diffs only (this means that the keys are the same as in the common file), let's call it diffs and use i18next namespace fallback feature.
In a specific place you can use diffs namespace (which will load diffs.json file) and fallback to your common namespace for missing keys.
Since your config is already defined common as a defaultNS, all you need to do is just for the specific user change the namespace to diffs.
<div class="outer" data-i18n="diffs:key"></div>
// -----------------------------^
$(".outer").localize();
You can define the namespace for a specific region of translation
$(".outer").localize({ns: 'diffs'});
// this will call translation on the `.outer` div with a specific namespace without the need to attach it as I've showed before

How to manipulate a JSONArray in JQuery

i have a php function which returns me this code in JSON
{"0":{"title":"Dans l\u2019appartement"},"1":{"title":"A l\u2019a\u00e9roport - D\u00e9part de B\u00e9atrice"},"2":{"title":"Visite chez Jean-Louis"},"3":{"title":"Anita \u00e0 la matenit\u00e9"},"4":{"title":"Visite chez Jean-Louis 2"},"5":{"title":"H\u00e9l\u00e9na pr\u00e9sent\u00e9e \u00e0 la famille"},"6":{"title":"Chez des proches"},"7":{"title":"Soir\u00e9e souvenir avec un proche - Photos, histoires"},"8":{"title":"Douceline tenant un b\u00e9b\u00e9"},"9":{"title":"Visite chez Jean-Louis 3"},"10":{"title":"Bapt\u00eame de Alexandra - Dans l\u2019\u00e9glise"}}
and i want to manipulated in JQuery I’ve did this but it doesn’t work
$.each(json, function(item, value) {
console.log(value);
$.each(value, function() {
console.log(this.title);
});
});
any ideas thanks a lot
The first traversal using each provides you the object containing the value of title field.
So , Simply fetch the value using :
$.each(json, function(item, value) {
alert(value.title);
});
And here is the demo jsfiddle

Read JSon string with Javascript and PHP

In a Javascript file i receive this JSon string into a hidden html string:
<input id="page_json_language_index" type="hidden" value="[{"id":"label_accept_terms","fr":"En cliquant sur le bouton ci-dessous, vous accepter de respecter les "},{"id":"label_and","fr":" et la "},{"id":"label_birthdate","fr":"Anniversaire"},{"id":"label_bottom_about","fr":"\u00c0 propos de GayUrban"},{"id":"label_bottom_contact","fr":"Contactez-nous"},{"id":"label_bottom_copyright","fr":"\u00a9 2010-2013 GayUrban.Com - Tous droits r\u00e9serv\u00e9s"},{"id":"label_bottom_privacypolicy","fr":"Vie priv\u00e9e"},{"id":"label_bottom_termsofuse","fr":"Conditions d`...mon courriel"},{"id":"label_signon_twitter","fr":"Avec Twitter"},{"id":"label_slogan","fr":"LE site des rencontres LGBT !"},{"id":"label_terms_of_use","fr":"Conditions d`utilisation"},{"id":"label_title","fr":"Bienvenue sur GayUrban | LE site des rencontres LGBT !"},{"id":"label_transgender","fr":"Transgendre"},{"id":"label_username","fr":"Nom d`utilisateur"},{"id":"label_wait_create_profile","fr":"Un moment SVP, Cr\u00e9ation de votre profil en cours..."},{"id":"label_your_gender","fr":"Votre \u00eate"}]">
from MySQL database in user language (this example is in French (fr) so, i need to access in Javascript to each "id" and each value of this 'id"
Example : for the first "id"
i need to obtain on separate variables for each ID and VALUE
var label = "label_accept_terms";
and other variable
var value = "En cliquant sur le bouton ci-dessous, vous accepter de respecter les "
so i have a problem to read and affected each ID with good label and value.
Thank you for your helping !
I must point out that you've made a mistake in your HTML. You should escape the quotes to avoid breaking attributes, for example, simply replace them with apostrophe:
<input id="page_json_language_index" type="hidden" value='[{"id":"label_accept_terms","fr":"En cliquant sur le bouton ci-dessous, vous accepter de respecter les "},{"id":"label_and","fr":" et la "},{"id":"label_birthdate","fr":"Anniversaire"},{"id":"label_bottom_about","fr":"\u00c0 propos de GayUrban"},{"id":"label_bottom_contact","fr":"Contactez-nous"},{"id":"label_bottom_copyright","fr":"\u00a9 2010-2013 GayUrban.Com - Tous droits r\u00e9serv\u00e9s"},{"id":"label_bottom_privacypolicy","fr":"Vie priv\u00e9e"},{"id":"label_bottom_termsofuse","fr":"Conditions d`...mon courriel"},{"id":"label_signon_twitter","fr":"Avec Twitter"},{"id":"label_slogan","fr":"LE site des rencontres LGBT !"},{"id":"label_terms_of_use","fr":"Conditions d`utilisation"},{"id":"label_title","fr":"Bienvenue sur GayUrban | LE site des rencontres LGBT !"},{"id":"label_transgender","fr":"Transgendre"},{"id":"label_username","fr":"Nom d`utilisateur"},{"id":"label_wait_create_profile","fr":"Un moment SVP, Cr\u00e9ation de votre profil en cours..."},{"id":"label_your_gender","fr":"Votre \u00eate"}]'>
JSON.parse is the best way to convert JSON string, but it's not surpported by old IE (e.g. IE6). You can use JSON2 to make it compatible, or just simply use eval().
Aware that abuse of eval() may lead to XSS (Cross Site Scripting) vulnerability. Make sure that the JSON you're about to parse is safe (doesn't include malicious Javascript).
Here's an example to read all id:
<input id="page_json_language_index" type="hidden" value='[{"id":"label_accept_terms","fr":"En cliquant sur le bouton ci-dessous, vous accepter de respecter les "},{"id":"label_and","fr":" et la "},{"id":"label_birthdate","fr":"Anniversaire"},{"id":"label_bottom_about","fr":"\u00c0 propos de GayUrban"},{"id":"label_bottom_contact","fr":"Contactez-nous"},{"id":"label_bottom_copyright","fr":"\u00a9 2010-2013 GayUrban.Com - Tous droits r\u00e9serv\u00e9s"},{"id":"label_bottom_privacypolicy","fr":"Vie priv\u00e9e"},{"id":"label_bottom_termsofuse","fr":"Conditions d`...mon courriel"},{"id":"label_signon_twitter","fr":"Avec Twitter"},{"id":"label_slogan","fr":"LE site des rencontres LGBT !"},{"id":"label_terms_of_use","fr":"Conditions d`utilisation"},{"id":"label_title","fr":"Bienvenue sur GayUrban | LE site des rencontres LGBT !"},{"id":"label_transgender","fr":"Transgendre"},{"id":"label_username","fr":"Nom d`utilisateur"},{"id":"label_wait_create_profile","fr":"Un moment SVP, Cr\u00e9ation de votre profil en cours..."},{"id":"label_your_gender","fr":"Votre \u00eate"}]'>
<textarea id="debug-console" cols="50" rows="20"></textarea>
<script type="text/javascript">
var arr = eval(document.getElementById("page_json_language_index").value),
output = document.getElementById("debug-console");
//output all id
for(var i=0; i<arr.length; i++)
output.value += [i, ": ", arr[i].id, "\n"].join("");
//show the first id
alert(arr[0].id);
</script>
Actually you can directly output JSON to Javascript.
To meet your needs, I think here's what you need.
<?php
...
$data = ...; //for example, from mysql query results
$language = "fr"; //you can replace it with it/en/zh...
...
?>
<input id="some_id"></input>
<script>
(function() {
var i18n = "<?php echo json_encode($data); ?>",
lang = "<?php echo $language; ?>", //language
data = eval(i18n); //you can also use JSON.parse/jQuery.parseJSON ...
for(var i=0; i<data.length; i++) {
document.getElementById(data[i].id).value = data[i][lang]; //a general way to read object's attribute in Javascript
}
})()
</script>
i need to obtain on separate variables for each ID and VALUE
This is not the way to go, you don't want to pollute your scope with a bunch of variables. What you have is a collection (array of objects). You can loop such collection and access the properties you need.
var input = document.getElementById('page_json_language_index');
var data = JSON.parse(input.value); // collection
the goal is to assign to each pair of (id, fr) value into a jquery
label
var label = function(lab) {
return '<label id="'+ lab.id +'">'+ lab.fr +'</label>';
};
var labels = data.map(label);
You can also make it a jQuery collection:
var $labels = $(labels.join(''));
Then you can append it to any container:
$labels.appendTo('body');

Categories