How to make a page for every single object from JSON data - JavaScript - javascript

I've JSON data
[{"name":"Zohir","id":"151232", "code":"ZO"},{"name":"Tuhhin","id":"151233", "code":"TU"}, .....]
I want to show every single object in different page & also i want to render a single student page based on "code", Like www.mylink.com/student/ZO
I don't know is my question correct or not, I'm new in JavaScript
I tried to show all data in a page from JSON file & i did that, but i can't render a single student page
function getStudent() {
fetch('https://myjesondatas123211.herokuapp.com/v/students')
.then((res) => res.json())
.then((data) => {
let output = '<h2>Students</h2>'
data.forEach(function (student) {
output += `
<div class="col-md-4">
<h4>${student.name}</h4>
<p>${student.id}</p>
<p>${student.code}</p>
</div>
`;
});
document.getElementById('output').innerHTML = output;
})
};

A solution to this problem would be fairly complex to create in plain Javascript.
You would need to have an understanding about single page applications and routers to start tackling this problem.
You might want to look over here or search for another tutorial to get the basics:
https://dev.to/rishavs/making-a-single-page-app-in-ye-good-olde-js-es6-3eng

You want to do a single-page app, which is not simple in plain javascript.
You may want to consider using frameworks for this, such as Angular or React to do this quite easily
They have native routers and allow you to create routes with parameters, and display a component depending on this parameter.

Related

Best way to translate inputs

Good evening,
Today I've encountered a question/problem. I'll get right into it. So basically I have form which is used to create meal. Meal table (migration) looks like this:
$table->uuid('id')->primary();
$table->uuid('restaurant_id')->nullable();
$table->string('name_lt', 100);
$table->string('name_en', 100);
$table->string('name_ru', 100);
$table->smallInteger('prep_time');
$table->string('image', 150);
$table->boolean('visibility')->default(0);
$table->boolean('deleted')->default(0);
$table->timestamps();
$table->foreign('restaurant_id')->references('id')->on('restaurants')->onDelete('cascade');
Aside the there's tons of other stuff, like ingredients and stuff, which are related to that specific meal. In the form page I have 3 different forms for different languages that is my native lithuanian, english and russian. There is tab buttons for changing form to other language, all it does is just hide current form and show another (there is 3 identical forms in 1 page).
What I'm trying to achieve is if I fill in lithuanian language's inputs, I want english and russian inputs to be filled also (that can be achieved with jquery or javascript change function), but it should fill in translated text.
Simple example:
In first form I fill in text name_lt = 'Obuolys', so name_en and name_ru should get filled too, but in different language, in this case name_en = 'Apple', name_ru = 'яблоко'
I never used translation api's so I'm wondering what would be the best way, I'm thinking of using DeepL as it is quite cheap.
If someone could give me some advices or simple example would be nice, I could follow on from that.
If you want to use javascript, you could use a button's click event to fill out the other fields before submiting the form. If I understand it correctly you have 3 forms (1 per tab).
You could do something like this for each form.
<form id="form-lt" method="post">
#csrf
<input name="name_lt">
<input type="hidden" name="name_en">
<input type="hidden" name="name_ru">
{{-- Not a true submit button --}}
<button id="button-lt type="button">Submit</button>
</form>
Given a function that takes text input, the original language and the language you want to translate
async function translate(text, from_language, to_language) {
const response = await fetch(...);
const data = await response.json();
// get translated text from data
return translated_text;
}
The js part could look like this
const button_lt = document.getElementById('button-lt');
button_lt.addEventListener('click', async event => {
const form = event.target.form;
const lt_value = form.querySelector('[name=name_lt]').value;
const en_input = form.querySelector('[name=name_en]');
const ru_input = form.querySelector('[name=name_ru]');
en_input.value = await translate(lt_value, 'lt', 'en');
ru_input.value = await translate(lt_value, 'lt', 'ru');
form.submit();
});
Alternatively, if you want to do it server-side, you could try to call whatever translation API you end up using using the Http facade provided by laravel before validating the input data or before saving the model to the database.
Are you using PHP or javascript?
DeepL offers a NodeJS library (for the backend) and a PHP library to easily allow you to translate. For example, to translate in PHP, you can use the following snippet after installing the library:
$authKey = "f63c02c5-f056-..."; // Replace with your key
$translator = new \DeepL\Translator($authKey);
$result = $translator->translateText('Hello, world!', null, 'fr');
echo $result->text; // Bonjour, le monde!
To perform this when your users fill in some text, you will need to write the appropriate Laravel code. Please note that it is not safe to do this in the frontend, as it requires you to expose your $authKey.

What are the best practices of storing data for dynamic content in html?

Basically, I'm creating a simple brochure website that can change contents dynamically using Javascript. Every time the button is clicked, it calls a function in the .js file which inserts it to the html. To do this, I put these data into a variable in the .js file. The problem is that I find the data too large and is cluttering the .js file.
<button class="content-1">
<button class="content-2">
<div class="container">
# change between content 1 and 2
</div>
// in my case there are more than 2 contents
// each content has other contents as well
// the question is where to put these data
let contentOne = [
"a lot of text data",
"a lot of text data",
"a lot of text data"
]
# other code
For now I managed to separate them into another .js file. But I'm just wondering, is there a cleaner way to store and then access these data? Like using YAML ? How do you usually do it ?
For dynamic websites I realize it's usually stored in databases, but how is it for static websites
I would put it in a different file as JSON. Then in your HTML file, you have a function that does a fetch request to get the JSON file from the server.
This does mean that you need a webserver while you are developing. You can use a light-weight one like http-server.
Then, your code does something like this:
function hydrateData() {
return fetch('data.json').then(response => response.json());
}
hydrateData().then(data => {
// the rest of your code that needs the data goes in here
})

Formatting data from Firebase with HTML and CSS

This time I'm facing a problem with formatting data from Firebase. This is how structure in my database looks:
I'm getting it from database using this code:
const preObject = document.getElementById('object')
var parametryObject = firebase.database()
.ref('Parametry_powietrza')
.limitToLast(1)
.once('value').then(function(snapshot) {
var listaParametrow = snapshot.val();
console.log(listaParametrow);
preObject.innerText = JSON.stringify(snapshot.val(), null, 3)
});
And on my webpage it looks like:
My question is - how to properly refer to that data to be able to change its appearance using HTML and CSS?
Thank you! :)
It looks like you're trying to access the data inside your JSON object being returned to you from your FireBase RealTime database (RTDB). But the way you've structured your data makes it near impossible for your javascript to iterate through it.
Some pointers I can give you regarding your data in the Realtime Database atm:
1) Datetime is typically stored in what's called Epoch Time. Which is typically the number of seconds since Jan 1, 1970. The number can easily be converted back into text using various javascript time libraries. An easy one to try out is Luxon. You can see epoch time with this online convertor here.
2) Secondly, RTDB supports the creation of unique, sequential, sortable "push-id" whenever you call the .push({ myDataObject }) function. So there's no need to store the date and the time as the "keys" to your object. More info about the push-id here and here. It's really interesting stuff!
3) I hate to be writing this suggestion because it seems like taking a step back before you can take steps forward, but I feel like you would benefit alot on looking at some articles on designing databases and how to sensibly structure your data. Firebase also has a great introduction here. If it's any help, for your data structure, I suggest modifying your data structure to something like below:
{
Parametry_powietrza: {
[firebase_push_id]: {
timestamp: 726354821,
Cisnienie: 1007.78,
Temperatura: 19.23,
Wilgotnosc: 52.00,
},
[firebase_push_id]: {
timestamp: 726354821,
Cisnienie: 1007.78,
Temperatura: 19.23,
Wilgotnosc: 52.00,
}
}
}
That way, when firebase returns your data, you can iterate through the data much more easily and extract the information you need like:
database
.ref('Parametry_powietrza')
.limitToLast(10)
.once('value', snapshot => {
snapshot.forEach(child => {
// do what you need to do with the data
console.log("firebase push id", child.key);
console.log("data", child.val());
})
});
All the best! BTW are you using any javascript frameworks like React or Vue?

Using handlebars.js for dynamic user content?

Handlebars is commonly used on static predefined html templates and then given dynamic data via JSON, but what if the template itself comes from json?
I'm trying to build a community forum whereby I have a template that gets filled in for where the users post goes. The post itself however also contains template information (which is dynamic). How can I get handlebars to process a dynamic template that just came out of ajax?
For example, a users post can contain any or all of the following in any order: text, pictures, links, videos, etc.
The content will look something like this:
{{text-open}} blablabla heres a picture {{text-close}}{{image-open}}
http://someRandomUrl.com {{image-close}} {{image-open}}
http://anotherRandomUrl {{image-close}}
I'm not sure how to do this with handlebars. I have the feeling maybe I should just use a string replace function? But would that be the optimal method?
You just have to compile the template:
fetch("post.hbs")
.then(source => Handlebars.compile(source))
.then(postTemplate => {
// Do stuff, then fill the template:
postElement.innerHTML = postTemplate(postData);
});

Storing HTML in Firebase (AngularFire), good idea or bad?

Is it a good idea to store HTML in Firebase (AngularFire)?
I have a website where I am creating an admin site where users can make HTML elements. I want people to save these elements and the order and the content within the elements. So I thought it would be much easier to just store the whole HTML as a string and load it in when they return. Bad idea?
Here is what I have (simplification):
$scope.save = function() {
var refState = new Firebase("https://<name>.firebaseio.com/users/" + currentAuth.uid + "/state");
var html = "<div>hello</div>";
refState.set({
"state": html
}, function(error) {
if (error) {
console.log("not been saved")
}
})
}
And in my HTML I retrieve want to display it like this using Angular, (yeah I know now how to render HTML in Angular thanks to the comments :)
<div class="well col-md-12">
{{sync[3].state}}
</div>
Storing stringified HTML in firebase is no worse than storing it in a different datastore. You'll want to consider XSS issues, including things like what if they define <style>body{display:none}</style> in their html.
Are you creating a real full fleshed content creation system? If so, it's sometimes hard to get away from user defined HTML, usually from CKeditor, tinymce, etc. However, if the items that they're building are all similar, you should consider how you can store/restore them in a better data format. Most of the time there is a better way to save and restore user defined content that storing straight HTML.
I'd suggest checking out Firepad.
Firepad is a drop-in "Open source collaborative code and text editing" experience for Firebase apps.
"Firepad can use either the CodeMirror editor or the Ace editor to render documents."
Easily allows for a rich text-editor experience that seamlessly stores/syncs the content in a Firebase instance.
As the documentation describes, this is how you initialize Firepad:
<div id="firepad"></div>
<script>
var firepadRef = new Firebase('<FIREBASE URL>');
var codeMirror = CodeMirror(document.getElementById('firepad'), { lineWrapping: true });
var firepad = Firepad.fromCodeMirror(firepadRef, codeMirror,
{ richTextShortcuts: true, richTextToolbar: true, defaultText: 'Hello, World!' });
</script>
It's perfectly fine to store HTML in Firebase.
Koding.com, Nitrous.io, and more use Firepad for their collaborative code editor products.
I think it's very bad idea to store html in firebase, store only pain text
How to render html with angular templates

Categories

Resources