Use JSON after caching through AJAX - html

I'm new in coding and currently creating a website that supports English and Russian languages. I want to change between them with no page reload, so I decided to use AJAX to achieve it and store information in JSON. I have a checkbox that changing my langString between EN and RU depending on checkbox state.
var langStr = "en";
$('#langsw').click(function(){
if($(this).prop("checked") == true){
console.log("Checkbox is checked.");
langStr = "ru";
}
else if($(this).prop("checked") == false){
console.log("Checkbox is unchecked.");
langStr = "en";
}
});
And this is jquery code to perform AJAX part
$.ajax({
type:'GET',
dataType:'json',
url: langStr+".json",
cache:true,
success: function(data){
$('#meet').append(data.title);
$('#meet').append(data.hr);
$('#meet').append(data.subtitle);
},
error: function(data){
console.log("there is an error")
}
});
My JSON is
{
"title":"<h1 style=\"color:white; font-size: 42pt\">Name</h1>",
"hr":"<hr style=\"width:60%\">",
"subtitle":"<h1 style=\"color:#dbdbdb; font-weight:100\">Interactive resume</h1>"
}
and the second one is the same in Russian.
Now the question: I want to cache both JSONs and then use one of them depending on the state of the checkbox, but I don't know how to do so. If you have any ideas relating to other ways of achieving this I will be very happy to read them.
P.s English is my 2 language so forgive the mistakes.

You can save the information in localstorage (altough there is a limit of how much you can save there).
You can use this formula to save raw json into localstorage
localStorage.setItem('language-ru', data);
To get what is in localstorage you would use
const ru = localstorage.getItem('language-ru')
So you can check, if user has the right language in his localstorage and if there is nothing, you can download it with that ajax call.
You can read more about localstorage here: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

Related

Can i send data from one website’s console to another?

So im trying to automate a task at work, and im wondering if theres anyway to send data from the console of one webpage to the console of another web page.
The task i am trying to automate consists of a website that has a prefilled form. I need to get elements from this form, and then copy them into another totally different website. Ive already written a script that pulls the data i need from the form and displays it in the console. Now I need to find a way to send the data (which is simply variables) to the other page’s console. Is this possible?
Keep in mind this is in a work computer, not allowed to download anything on it.
Are you an admin of the webpages and are these pages from the same site? if the answer is yes, i would recommend you use localStorage for saving and retrieving the data then display it to the console.
If it's not your website and you want it to work anyway just create a simple browser extension.
Here are some links to help you get started with extensions
MDN doc
Chrome doc
The idea is for you to target webpage A collect the data and post it to Github
Then target webpage B to read data from your github gist and you dispaly it in the console.
Cheers, i hope it was helpfull
Which server side language are you using ?
Usually for these, you could just have a form which is posting data to another website's form.
Look at this php example :
https://www.ostraining.com/blog/coding/retrieve-html-form-data-with-php/
Correct me If I did not understand your question correctly.
//Store the logs in following way
console.stdlog = console.log.bind(console);
console.logs = [];
console.log = function(){
console.logs.push(Array.from(arguments));
console.stdlog.apply(console, arguments);
}
//copying the logs into a json file
(function(console){
console.save = function(data, filename){
if(!data) {
console.error('Console.save: No data')
return;
}
if(!filename) filename = 'console.json'
if(typeof data === "object"){
data = JSON.stringify(data, undefined, 4)
}
var blob = new Blob([data], {type: 'text/json'}),
e = document.createEvent('MouseEvents'),
a = document.createElement('a')
a.download = filename
a.href = window.URL.createObjectURL(blob)
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
a.dispatchEvent(e)
}
})(console)
console.save(console.logs) //prints the logs in console.json file
// from the console.json file, you can use log information from another page
//Store the logs in following way
console.stdlog = console.log.bind(console);
console.logs = [];
console.log = function(){
console.logs.push(Array.from(arguments));
console.stdlog.apply(console, arguments);
}
localStorage.setItem('Logs', console.logs);
localStorage.getItem('Logs'); // from any browser

How to build a multilingual website with Polymer?

I don't want to duplicate my components or use templating application.
Then, how can I do that?
you could do something like the chrome.i18n api for chrome apps and extensions. https://developer.chrome.com/extensions/i18n the general idea is each language has a json file with all the text. sub foldered by language.
_locals
\- en
| \- messages.json
- es
\- messages.json
content of the json file just needs to be valid json. nothing exciting just key value pairs
messages.json
{
elementName: 'my-element',
elementVersion: '0.1'
}
the user of the element could set the language with a attribute
<my-element language="en"></my-element>
then in your element you would make a XMLHttpRequest to get the text.
getLanguageText: function() {
var xhr = new XMLHttpRequest();
var url = '/my-element/_locals/' + this.language + '/messages.json';
xhr.open("GET", url, true);
xhr.responseType = 'json';
xhr.send();
xhr.onload = function (e) {
this.text = e.target.response;
}.bind(this);
xhr.onerror = function (e) {
console.error('Error Loading Language Text', e);
};
};
the real issue i guess with this approach is it being dependent on path of the json file staying static. not a real big deal if everyone is going to get the element from say bower where it will always be in the bower_components/my-element/_locals/en/messages.json location.
then you could use the values in your html just like any other polymer value.
{{text.elementName}}
maybe this will help. /shrug
edit: i didn't see this # time of post but you might need to bind this to the onload callback. in the original answer this would be the xhr object. by using .bind(this) the callback would correctly target the custom element. ill edit answer.

Calling a PHP script on button press with Sencha Architect

I've been looking at the documentation and tutorials for Sencha Architect, and I can't figure it out. What I want to is have a button press post a value to a PHP script on a server, and then retrieve the result from a PHP session variable. From what I've seen, I'm not sure if I can get it to call PHP at all, much less read a session variable.
I realize there may be a few questions in here (connecting the button to a controller/store, calling the script, reading the result), but I don't know enough about Architect to know if they're the correct ones.
EDIT: I think I've got the button connected to a controller, but I'm still not sure how to get it to call the PHP script.
EDIT 2:
I added a BasicFunction to the button, but I can't get it to work. Here's the code:
// Look up the items stack and get a reference to the first form it finds
var form = this.up('formpanel');
var values = form.getValues().getValues()[0];
Ext.Msg.alert('Working', 'Loading...', Ext.emptyfn);
Ext.Ajax.request({
url: 'http://wereani.ml/shorten-app.php',
method: 'POST',
params: {
url: values
},
success: function(response) {
Ext.Msg.alert('Link Shortened', Ext.JSON.decode(response).toString(), function() {
form.reset();
});
},
failure: function(response) {
Ext.Msg.alert('Error', Ext.JSON.decode(response).toString(), function() {
form.reset();
});
}
});
Also, is that the correct way to get the value from the field (itemID:url)? I couldn't find anything in the documentation for Touch about that.
Use an Ext.Ajax request in the listener for the button. docs.sencha.com/touch/2.2.1/?mobile=/api/Ext.Ajax.
The documentation there is pretty straightforward. If you have trouble please post some specifics and I'll try to write you an example.
Good luck, Brad

HTML5 offline JSON doesn't work

I have a small HTML5 (using jQuery mobile) web app that caches its files to use them offline, however some parts don't seem to work once it's offline.
The files are cached OK (I can see them in the web inspector) but when I try to visit a page that uses jQuery to load a JSON file it doesn't load.
I tried creating an empty function to load the JSON files (when the index page is loaded) to see if that would help but it doesn't seem to make a difference.
Here's the function that doesn't want to work offline.
My question is: should it work offline or am I missing something?
// events page listing start
function listEvents(data){
$.getJSON('/files/events.json', {type: "json"},function (data) {
var output = '';
for (i in data)
{
var headline = data[i].headline;
var excerpt = data[i].rawtext;
output += '<div id="eventsList">';
output += '<h3>'+headline+'</h3>';
output += '<p>'+ excerpt +'<p>';
output += '</div>';
}
$("#eventsPageList").html(output).trigger("create");
});
}
I'm not really sure, if i'm right about this. But i think an ajax request will always fail when you are offline. It won't use the locally cached file. What you should try is, to cache the data in localStorage. When the ajax request fails, fallback to localStorage.
OK here's a version which seems to work, I read the json file and place it in localstorage then use the localstorage in the listEvents function.
When the page loads I call this function to add the json to localstorage
function cacheJson(data){
$.getJSON('/files/events.json',
{type: "json", cache: true},function (data) {
localStorage['events'] = JSON.stringify(data); });
}
Then this function to output the json (from localstorage) to the page, with an if else incase the localstorage doesn't contain the json.
function listEvents(data){
if (localStorage.getItem("events") === null) {
var output = '';
output += 'Sorry we have an error';
$("#eventsPageList").html(output).trigger("create");
}
else {
data = JSON.parse(localStorage['events']);
var output = '';
for (i in data)
{
var headline = data[i].headline;
var excerpt = data[i].rawtext;
output += '<div id="eventsList">';
output += '<h3>'+headline+'</h3>';
output += '<p>'+ excerpt +'<p>';
output += '</div>';
}
$("#eventsPageList").html(output).trigger("create");
}
}
It seems to work ok but am I missing something that could cause issues?
Is there a more efficient way of doing this?

Get request within page

I've been looking around, but I'm not quite sure what to search for...
I want to have a webpage send a Get request to a python script when you first open the page, maybe with the option to refresh it with a button. Is there a way to send a request ("script.py?var=test") and display the results within the page?
What I tried to use earlier: (didn't work..)
Am I doing something stupid? I don't know anything about JavaScript
<p>Highscores:</p>
<p id='scores'>text</p>
<input type='button' onclick='changeText()' value='Change Text'/>
<script type="text/javascript">
function changeText(){
var request = new XMLHttpRequest();
request.open("GET", "../../cgi-bin/highScore.py?scoreMethod=load&game=ulama", true)
request.onreadystatechange = function(){
var done = 4, ok = 200;
if (request.readyState == done && requeset.status == ok){
document.getElementById('scores').innerHTML = request.responseText;
}
};
request.send();
}
</script>
Also, should I have the python script return a full page with the header and all? or just the relevant section?
Use a Jquery call in this case to clean up your code a little bit.
Also in this case you should use a post because of the nature of your 'beast' :)
function changeText(){
$.ajax({
method : "POST",
URL : "../../cgi-bin/highScore.py",
data : {
"scoreMethod" : "load",
"game" : "ulama"
},
success : function(data) {
$("#scores").html(data);
}
});
}
I'd also look into JSON and jquery being returned as its probaly going to be easier in the long term (Though ive never played with python.
why not using jquery for doing this?
$('#scores').load('../../cgi-bin/highScore.py?scoreMethod=load&game=ulama', function(responseText, textStatus) {
alert(textStatus);//check here whether textStatus equals 'success' or something else (maybe an error)
});