Best way to translate inputs - javascript

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.

Related

Add Signature field to pdf in javascript

after hours of searching for a solution, I've decided to ask my first question on stackoverflow.
Our application uses pdf-lib (https://www.npmjs.com/package/pdf-lib) to modify existing PDFs, e.g. add images. We're now looking for a way to ad signature form fields to the PDF as well.
With pdf-lib, it is possible to add a bunch of form fields, except for signature fields. It is possible to get them (https://pdf-lib.js.org/docs/api/classes/pdfform#getsignature), but unlike other fields, there's no create method (e.g. https://pdf-lib.js.org/docs/api/classes/pdfform#createtextfield).
I've digged deeper in the code, and found access to the PDFForms AcroForm (https://pdf-lib.js.org/docs/api/classes/pdfform#acroform). It's possible to add fields with it, but I wasn't able to create the correct Field beforehand (in my opinion it has to be PDFSignature or PDFAcroSignature).
I found out that other fields like PDFAcroText have create methods
class PDFAcroText extends PDFAcroTerminal {
static fromDict = (dict: PDFDict, ref: PDFRef) => new PDFAcroText(dict, ref);
static create = (context: PDFContext) => {
const dict = context.obj({
FT: 'Tx',
Kids: [],
});
const ref = context.register(dict);
return new PDFAcroText(dict, ref);
};
Those get called by the wrapper functions (like createTextfield as mentioned):
createTextField(name: string): PDFTextField {
assertIs(name, 'name', ['string']);
const nameParts = splitFieldName(name);
const parent = this.findOrCreateNonTerminals(nameParts.nonTerminal);
const text = PDFAcroText.create(this.doc.context);
text.setPartialName(nameParts.terminal);
addFieldToParent(parent, [text, text.ref], nameParts.terminal);
return PDFTextField.of(text, text.ref, this.doc);
}
I looked for other js libs that provide the possibility to add signature form fields, but I wasn't able to find the answer to this - except for pay to use libs like pdfjs.express.
Assuming that they are capable of adding such fields, there must be a way to do this!
Please let me know if anyone of you figured out how to do this or if there's another solution for this.
Thank you in advance!
Greetings
Alex
The Acrobat PRO itself doesn't have an option to put a straight "Signature" field. You may "request" a signature, but only using Adobe's services, and an email is required.
If you plan to add a signature by the code, take a look at their "Fill Form" example. They put an image on top of a Button field, but an Image field also works.
const signatureImageField2 = form.getButton('button-signature-field')
signatureImageField2.setImage(signatureImage)
const factionImageField = form.getField('image-signature-field_af_image')
factionImageField.setImage(signatureImage)

How to make a page for every single object from JSON data - 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.

Connect Array across files

So I'm making a javascript game and I have three files. The first file looks something like this:
var player_items = [];
The second file has a button that pushes an item into the array:
player_item.push("sword");
In the third file, I have a console log that shows me the items:
console.log(player_items);
So then when I go to play my game, I can create the item in the second file, but it is not pushing to the third files so I can use them. I have connected all the files with
<script type="text/javascript" src="player_items.js"/></script>
Any ideas?
I think I understand what you want to do so I'll post an answer.
In order to get information from a form you will have to use a server-side language such as PHP to do this.
select.html --> play.html
Basic form submission using php: http://php.net/manual/en/language.variables.external.php
Now there is a way without php but it leaves your values exposed to a URL string. such as mygame.com?x=50&y=70&z=6560
So on select.html we have a form
<form action="play.html">
<input name = "x"></input>
<input name = "y"></input>
<input name = "z"></input>
</form>
And in game we use javascript to read the parameters in the url using document.location.search:
var x = document.location.search.split("=")[1].split("&")[0]
var x = document.location.search.split("=")[2].split("&")[0]
var y = document.location.search.split("=")[3]
But this will leave a vulnerability where someone can inject their own values.
Hope this helps.

Ajax passing php variable to javascript function as an argument

I have three tables in my database: Person (id, name, last_name), System (id, name), PersonInSystem(id, person_id, system_id). The last one is used to link a person with a system.
I use <select> to display every person from my DB like this
echo '<option value="'.$queryResult["id"].'">'.$queryResult["name"].' '.$queryResult["last_name].'</option>';
I use Ajax to get the id and to send a query SELECT * FROM Person WHERE id = ID_FROM_SELECT. Then, I display the data like this (I can't copy the code, so I have to rewrite it from head, I will use pseudo PHP + HTML), and the main purpose of it is to edit a chosen person:
<form>
Name: <input type="text" value="'.$nameFromDB.'" name="name">
Last name: <input type="text" value="'.$lastNameFromDB.'" name="lastname">
System: while () { // if one person is assigned to many systems, I will display them all in separate selects
<select><option value="'.$systemAssignedToPerson.'">'.$systemAssignedToPerson.'</option>
while () {
// display every system except for the one listed above
}
</select><img src="drop.gif" onclick="deleteSystem(document.getElementById(\"system\").value)"><input type="hidden" id="system" value="'.$systemAssignedToPerson.'">
}
<input type-"submit" value="Edit" name="editPerson">
</form>
Now if I want to unassign a person from given system, I would like to click the drop.gif image and trigger deleteSystem(value) function, which will send query DELETE FROM PersonInSystem WHERE system_id = SYSTEM_ID_SENT and person_id = PERSON_ID_SENT, but I can't pass the value and I don't have really idea how to do it (I'm new with Ajax).
I can store person's id in a session variable, but I don't know how to send system id, and also I don't want to sent the data to another page.
Also I would like to refresh the page with changed system assignment (the same person should be displayed).
I think you need native javascript function call to the server
function deleteSystem(value){
var deleteflag=confirm("Are you sure to delete?!!");
if(deleteflag){
//setup your request to the server
window.location='delete.php?SYSTEM_ID_SENT='+value
}
}
In your delete.php file you can get the SYSTEM_ID_SENT in this way
$id=$_GET['SYSTEM_ID_SENT'];
$personid=$_SESSION['your session variable name'];
// run your delete query
$delqry=mysql_query("");
if($delqry){
//redirect to the page you want
header('location:yourpage.php');
}
Change the code as below.
It should work
<img src="drop.gif" onclick="deleteSystem('<?php echo $systemAssignedToPerson;?>')">
Your deleteSystem JavaScript function needs to send the following kind of request to the server:
(Example: Handler file for unassign)
"unassign.php?systemId=459&personId=300"
(Example: Generic handler file)
"handler.php?systemId=459&personId=300&action=unassign"
In unassign.php:
$systemId = $_GET["systemID"];
$personId = $_GET["personID"];
/* Your SQL stuff here -
statement something like
DELETE FROM PersonInSystem WHERE person_id = "$personId" AND system_id = "$systemId" */
Improvements:
* Use a javascript library like Prototype (oldschool, lightweight) or jQuery (more heavy) for handling the Ajax stuff
* Use $_POST and post variables instead of $_GET
* Use a library for properly quoting your SQL
* Care about html special characters and proper input validation/filtering

Dumbed down Powershell web client function to let me post form data easily

Ive been using an Internet Explorer automation script found here:
http://www.pvle.be/2009/06/web-ui-automationtest-using-powershell/
That lets me easily post form data using commands (functions) like this:
NavigateTo "http://www.websiteURI/"
SetElementValueByName "q" "powershell variable scope"
SetElementValueByName "num" "30"
SetElementValueByName "lr" "lang_en"
ClickElementById "sb_form_go"
The above would let me post values to elements and click to submit the form.
I would like to do the equivalent with Powershell's web client using helper functions. I haven't found such a script. The closest I could find was The Scripting Guys, Send-WebRequest:
http://gallery.technet.microsoft.com/scriptcenter/7e7b6bf2-d067-48c3-96b3-b38f26a1d143
which I'm not even sure it does what I expect (since there's no working examples showing how to do what I want).
Anyway, I'd really appreciate some help to get me started to do the equivalent of what I showed up there with working examples (as simple as possible). A bonus would be to also be able to get a list of element names for a URI in order to know what form elements I want to submit.
PS: I also need to be able to specify user-agent and credentials; so, examples with these included would be ideal.
Have you taken a look at the Invoke-WebRequest commmand? (requires powershell 3.0 or above) I believe the following would work for submitting the data
#POSTing data
Invoke-WebRequest http://www.websiteURI/ `
-UserAgent 'My User Agent' `
-Credential $cred `
-Method Post `
-Body #{
q = 'powershell variable scope'
num = 30
lr = 'lang_en'
}
For your bonus, the result of Invoke-WebRequest contains a collection of the InputFields on the page, which you can use to get a list of form elements to set.
#List input elements
Invoke-WebRequest http://www.websiteURI/ | select -ExpandProperty InputFields

Categories

Resources