Connect Array across files - javascript

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.

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.

Google Web App: Can't read or write on my label after evaluate the page

I have a label on my HTML page which shows number returned values. I can't read or change that when it is loaded? but locally I can do that with a console log.
<p name= 'message' id='ftext' > This team have
<label id="teams" > <?= teamSize ?> </label>
members. </p>
it returns null for both of these tag ids document.getElementById('team') or document.getElementById('ftext'), so I can't get their innerText or text Contents.
I am using HtmlService.createTemplateFromFile(file).evaluate() for rendering the page.
here is a link to my project: Attendance Form
Thanks for your help,
M
You said that document.getElementById('team') didn't work, but you actually named your id "teams".
If that fix doesn't work, can you share your code?
It's really frustrating to get variables between the frontend and the backend in GAS!
Something like this:
google.script.run
.withSuccessHandler(finishedOutput)
.withFailureHandler(errorOutput)
.split(); // SPLIT IS THE GS SCRIPT THAT PASSES BACK THE NUMBER YOU WANT
and then this
function finishedOutput(info) //INFO IS THE THING THAT GOT PASSED BACK BEFORE
{
var br='<br />';
var outputDiv = document.getElementById('status');
outputDiv.innerHTML = 'The spreadsheet has been split.' + br +'New files in this folder: ' + info.link + br ;
document.getElementById('process').style.display="none";
};
In my example I was passing back an object that had a info key but you can do this with a number or a string rather than an object.
these are both inside on the html page, and then the "split" function is on Code.gs and is a GAS function. Messy, right?

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

How go I get csv data into netsuite?

I've got an update to my question.
What I really wanted to know was this:
How do I get csv data into netsuite?
Well, it seems I use the csv import tool to create a mapping and use this call to import the csv nlapiSubmitCSVImport(nlobjCSVImport).
Now my question is: How do I iterate through the object?!
That gets me half way - I get the csv data but I can't seem to find out how I iterate through it in order to manipulate the date. This is, of course, the whole point of a scheduled script.
This is really driving me mad.
#Robert H
I can think of a million reasons why you'd want to import data from a CSV. Billing, for instance. Various reports on data any company keeps and I wouldn't want to keep this in the file cabinet nor would I really want to keep the file at all. I just want the data. I want to manipulate it and I want to enter it.
Solution Steps:
To upload a CSV file we have to use a Suitelet script.
(Note: file - This field type is available only for Suitelets and will appear on the main tab of the Suitelet page. Setting the field type to file adds a file upload widget to the page.)
var fileField = form.addField('custpage_file', 'file', 'Select CSV File');
var id = nlapiSubmitFile(file);
Let's prepare to call a Restlet script and pass the file id to it.
var recordObj = new Object();
recordObj.fileId = fileId;
// Format input for Restlets for the JSON content type
var recordText = JSON.stringify(recordObj);//stringifying JSON
// Setting up the URL of the Restlet
var url = 'https://rest.na1.netsuite.com/app/site/hosting/restlet.nl?script=108&deploy=1';
// Setting up the headers for passing the credentials
var headers = new Array();
headers['Content-Type'] = 'application/json';
headers['Authorization'] = 'NLAuth nlauth_email=amit.kumar2#mindfiresolutions.com, nlauth_signature=*password*, nlauth_account=TSTDRV****, nlauth_role=3';
(Note: nlapiCreateCSVImport: This API is only supported for bundle installation scripts, scheduled scripts, and RESTlets)
Let's call the Restlet using nlapiRequestURL:
// Calling Restlet
var output = nlapiRequestURL(url, recordText, headers, null, "POST");
Create a mapping using Import CSV records available at Setup > Import/Export > Import CSV records.
Inside the Restlet script Fetch the file id from the Restlet parameter. Use nlapiCreateCSVImport() API and set its mapping with mapping id created in step 3. Set the CSV file using the setPrimaryFile() function.
var primaryFile = nlapiLoadFile(datain.fileId);
var job = nlapiCreateCSVImport();
job.setMapping(mappingFileId); // Set the mapping
// Set File
job.setPrimaryFile(primaryFile.getValue()); // Fetches the content of the file and sets it.
Submit using nlapiSubmitCSVImport().
nlapiSubmitCSVImport(job); // We are done
There is another way we can get around this although neither preferable nor would I suggest. (As it consumes a lot of API's if you have a large number of records in your CSV file.)
Let's say that we don't want to use the nlapiCreateCSVImport API, so let's continue from the step 4.
Just fetch the file Id as we did earlier, load the file, and get its contents.
var fileContent = primaryFile.getValue();
Split the lines of the file, then subsequently split the words and store the values into separate arrays.
var splitLine = fileContent.split("\n"); // Splitting the file on the basis of lines.
for (var lines = 1,count=0; lines < splitLine.length; lines++)
{
var words = (splitLine[lines]).split(","); // words stores all the words on a line
for (var word = 0; word < words.length; word++)
{
nlapiLogExecution("DEBUG", "Words:",words[word]);
}
}
Note: Make sure you don't have an additional blank line in your CSV file.
Finally create the record and set field values from the array that we created above.
var myRec = nlapiCreateRecord('cashsale'); // Here you create the record of your choice
myRec.setFieldValue('entity', arrCustomerId[i]); // For example, arrCustomerId is an array of customer ID.
var submitRec = nlapiSubmitRecord(myRec); // and we are done
fellow NetSuite user here, I've been using SuiteScripts for a while now but never saw nlobjCSVImport object nor nlapiSubmitCSVImport .. I looked in the documentation, it shows, but there is no page describing the details, care to share where you got the doc from?
With the doc for the CSVImport object I might be able to provide some more help.
P.S. I tried posting this message as a comment but the "Add comment" link didn't show up for some reason. Still new to SOF
CSV to JSON:
convert csv file to json object datatable
https://code.google.com/p/jquery-csv/
If you know the structure of the CSV file, just do a for loop and map the fields to the corresponding nlapiSetValue.
Should be pretty straightforward.

Pass HTML form entries into a Javascript array to then be written to a client side cookie?

I'm building a bit of a test-case JS application, something very basic, but have run into some problems.
I'm trying to use a HTML form for a user to enter a number, which is then written to a Javascript Array. The user then has the option to write that same array to a local (client side) cookie. (I understand the security implications of this - it's a test-case and not for commercial use.)
However, I can't make the connection - how can I capture the HTML entry, press 'submit' which will send it to a JS array, where the user can then press a different 'submit' which will write the array to a text file?
If anyone can help I'd appreciate it because it's been nearly 6 hours and it's not funny anymore.
To read the data, use code such as this:
var data = new Array;
function readData() {
var inputs = document.getElementsByTagName('input');
for (i in inputs) {
if (!isNaN(i - 0) && inputs[i].type == 'text') {
data[i - 0] = inputs[i].value;
}
}
}
Trigger it with a button input:
<input type="button" onclick="readData();" value="Read" />
Still, do you want it as a cookie, a text file or what? Here are a few possible statements to use depending on which you want:
alert(data.toString());
window.location.href = 'data:text/plain,' + escape(data.toString());
document.cookie = 'data=' + data.toString();
The second one generates plain text that will likely be displayed in the browser. To save it as a text file, you'll have to either
do it manually after generating it
use some MIME type such as application/octet-stream instead of text/plain (then the user will have to name the file manually).
on the form add
<form bla bla bla onsubmit="return catchThings()">
<input name="test" id="test">
</form>
the with the javascript you can do
function catchThings(){
// get all the forms inputs by id
// do things with arrays or whatever
var example = document.getElementById("test").value;
return false;
}

Categories

Resources