javascript Arrays to mySQL - javascript

I have a file called translations.js, this js does got have two vars. This two vars are containing over 20.000 words.
var english = ["word1", "word2", "word3", "word4", ...]
var farsi = ["translation1", "translation2", "translation3",
"translation3"]
So i want to add all the values to a table on mySQL.
How can I do that quick and good? I want to do this with PHP.
I have the table "translations", containing this columns: id, english, farsi.
I want that all the words should be added into the database. So i thought to split this file into english.js and farsi.js - after that I wanted to use "explode" on both variables, foreach till no "" is there and then i wanted to add them step by step.
Is there a easier way? Does this way make sense?
Thank you!

If those arrays are valid json by themselves you could make a json file for each and read the file using file_get_contents(), then use json_decode() to convert to php array.
Loop over array to do inserts.
Alternative would be to load those variables into an html page and use ajax to post the whole array to php script. Loop over array received in $_POST

Does have english array and farsi array exactly the same size?
(I suppose yes).
Maybe you can create a file english.json and a farsi.json;
each file must only contains ["word1", "word2", "word3"] so remove var english =.
then use
$listEnglish = json_decode(file_get_contents('path_to_english.json'));
$listFarsi = json_decode(file_get_contents('path_to_farsi.json'));
It should generate a php array for each one.
finally loop on it
for($i = 0; $i < sizeof($listEnglish); $i++)
{
$englishWord = $listEnglish[$i];
$farsiWord = $listFarsi[$i];
//Then you insert
INSERT INTO translation(english, farsi) VALUES ($englishWord, $farsiWord);
}

Related

How to put PHP associative array into Javascript "associative" array

I have an associative Array in PHP and I want to transfer it into an Javascript on the fly, how can I do that?
My PHP array looks something like this:
$pairs = ["LBo"=>"Large Blocks",
"Bo"=>"Blocks",
"bo"=>" blocky"]
I get the PHP array size into JS using
const pairsSize= "<?php print(count($pairs)); ?>"
Next I create a loop in which the indexname of the associative array and the assigned value has to be read from the PHP array. I'm stuck and I don't know how to do it.
let lithPairs = []; //my JS "associative" array
for (x = 0; pairsSize> x; x++) {
....
}
I want the result to look like this;
lithPairs['LBo']="Large Blocks";
lithPairs['Bo']="Blocks";
lithPairs['bo']="blocky";
any help would be much appreciated!
use json encode php array and fetch it using URL or Cookies/ localstorage

How to search Steam game API JSON output?

I am working with following APIs:
http://api.steampowered.com/ISteamApps/GetAppList/v0002/?format=json
https://store.steampowered.com/api/appdetails?appids=GAMEID
(gameid example: "730" - counter strike)
My goal with both of these is to search them for data. For example I want the first API to give me a name of a game based on it's ID and the second one to give me specific information about a game for example if it has trading cards (id:29 in the API).
I tried a few things but I am kinda lost on this beacuse I don't really understand JSON so I would really appreciate some help.
I am open to both PHP and JS solutions.
IN PHP, you can use the json_decode() function to convert JSON data into an array. You can them access the values as you do for a classic array :
$appID = 730 ;
$url = 'https://store.steampowered.com/api/appdetails?appids=' . $appID ;
$content = file_get_contents($url) ; // retrieve the JSON data string from the website
$data = json_decode($content, true); // convert the JSON string into PHP array
echo $data[$appID]['data']['name'] ; // Counter-Strike: Global Offensive
var_dump($data[$appID]['data']['is_free']); // bool(true)

matching content of a file

I´m having a problem with a javascript function.
The idea is read the content of a file with javascript. Everything is working ok, I can see the content of the file, just now I want to organize the content.
And what I meant with organize is:
My file have a lot of strings, for example: tel#01234567#tel tel#01456789#tel dept#level1#dept dept#level4#dept.....
And everything is a line of strings, and at the end is that all what I see...
My goal is, when I read the file, at the end it have to show something like this:
Tel: 01234567
01456789
Dept: Level1
Level2
There is a way to have something like that?
function loaded(evt)
{
// Obtain the read file data
var fileString = evt.target.result;
document.getElementById('output').innerHTML = fileString;
}
So basically your file has attributes and data for the respective attribute surrounded by the attribute name + #?
The easiest thing would be to have the file in a common format for data, e.q. JSON. Then you could just use the attributes from the object you get by JSON.parse();
However, if you cannot change the file structure you will have to programm something that splits your string into the desired parts and creates an object out of the attributes to work with.
For the string you presented you could do one string.split(" ") to get every attribute singled out, resulting in an array like this:
Array [ "tel#01234567#tel", "tel#01456789#tel", "dept#level1#dept", "dept#level4#dept" ]
Afterwards you can iterate over the array and string.split("#") again for each element which gives you this:
array[0].split("#");
Array [ "tel", "01234567", "tel" ]
Then you can use the first index of the array as attribute name and the second one as its data. You could put that into an object and afterwards refer from the attribute straight to the data:
var string = "tel#01234567#tel tel#01456789#tel dept#level1#dept dept#level4#dept";
var array = string.split(" ");
var dataObject = {};
for(var i in array){
var element = array[i].split("#");
if(dataObject.hasOwnProperty(element[0])){
dataObject[element[0]].push(element[1]);
}else{
dataObject[element[0]] = [element[1]];
}
}
In the end you have an object that has all the attributes as its properties and the corresponding data stored in an array for each property. With that you should be able to work right? :)
When you read the file in you could use JS split to separate the content based on the delimiters.
Check it out here: http://www.w3schools.com/jsref/jsref_split.asp

How can I pass foreign characters (e.g. æ) to a javascript array from a PHP array?

I have an array of file paths, which is stored in a PHP array called $files, which I would like to pass to a javascript array using this command:
var files = <?php echo json_encode($files)?>;
Which is fine, however it doesn't pass any values which have special characters for example one that contains 'æ'. Instead that value in Javascript comes out as null. Is there another way of preserving these characters? The values are all file paths, which seem to be passed over OK using json_encode, just not these special characters.
I've solved it. I essentially ran through the array using url_encode, and THEN JSON'd that for Javascript to interpret.
$filesEncoded = array();
foreach ($files as $f) {
array_push($filesEncoded,urlencode($f));
}
<script>
var files = <?php echo json_encode($filesEncoded)?>;
</script>

How to dynamically update drop-down list options with values in a server-generated array

I have a web form with two drop-down boxes, and I'm looking for a way to dynamically update the options of the second box based on selections from the first.
The first box represents a data type, and the second box is a list of databases associated with the selected type.
I have the basic code running smoothly here:
var TypeA_DbSuffixList = ['Test1', 'Test2', 'Test3'];
var TypeB_DbSuffixList = ['TestA', 'TestB', 'TestC'];
function fill_dbSuffixList(){
document.getElementById("dbSuffixList").options.length = 0;
var suffixMenu = document.getElementById("dbSuffixList");
var dataFormat = document.getElementById("dataFormatType");
var suffixList = dataFormat.value + "dbSuffixList";
if (suffixList == 'TypeA_dbSuffixList') {
for(index in TypeA_dbSuffixList) {
suffixMenu.options[suffixMenu.options.length] = new Option(TypeA_dbSuffixList[index], index);
}
}
if (suffixList == 'TypeB_dbSuffixList') {
for(index in TypeB_dbSuffixList) {
suffixMenu.options[suffixMenu.options.length] = new Option(TypeB_dbSuffixList[index], index);
}
}
}
That code (activated whenever a selection is made in the dataType box) clears the existing list of options and repopulates the list based on the selected value of the "dataFormatType" box.
The problem that I face is that the actual lists of database tables are not hard coded and are instead generated with the following calls to the server to avoid repetitive editing of the page every time a new database is added:
var TypeA_dbSuffixList = ${TypeA_dbSuffixList};
var TypeB_dbSuffixList = ${TypeB_dbSuffixList};
These calls return the following code:
var TypeA_dbSuffixList = [Test1, Test2, Test3];
var TypeB_dbSuffixList = [TestA, TestB, TestC];
With the above code, the initial function treats each entry in the type arrays as an undefined variable, and nothing is ever written to the drop-down list.
If I were to add
var Test1 = "Apple";
var Test2 = "Orange";
var Test3 = "Grape";
prior to the "for" loop for TypeA, then selecting TypeA from the dataType drop-down list returns "Apple", "Orange", and "Grape" as the available databases for TypeA.
Visually, I see what needs to be changed. The [Test1, Test2, Test3] returns need to be ['Test1', 'Test2', 'Test3']. I'm just unsure exactly how to go about changing it, and have exhausted every web search I can think of.
Is there a way to either change the format of the returned arrays, or use the existing format and pass variable names as drop-down selections instead of using variable values?
Any help is greatly appreciated. I will continue to search for an answer on my own as well and will post it here should I find one.
I think the cleanest solution would be to change the code on the server-side to generate a proper JavaScript array of Strings, with the values enclosed in single or double quotes.
If that's not possible for some reason, and you want a pure-JavaScript solution, then I suggest you wrap the entire JSP/ASP/PHP variable (not sure what framework you're using) in double quotes, strip the string of brackets and spaces using a regex, and then split it into a string array using the comma as a delimiter.
So in your JavaScript, this:
var TypeA_dbSuffixList = ${TypeA_dbSuffixList};
would become this:
var TypeA_dbSuffixList = "${TypeA_dbSuffixList}".replace(/[\[\]\s]/g,"").split(",");
I think the best way to convert data in a server side language into something to be used in JavaScript is to JSON encode your objects.
I'm not sure what language your using on the server, but in PHP you can do the following
var arr = <?php echo json_encode( array ('abc', 'def', 'ghi') ); ?> ;
And your output will be
var arr = ['abc', 'def', 'ghi'] ;
This will make sure that strings with embedded new lines, tabs, quotes are properly escaped.
JSP
You said you're using JSP but the code you have looks more like velocity or free marker inside JSP. In JSP you could use the following, provided you download Gson
var TypeA_dbSuffixList = <%= new Gson().toJson(TypeA_dbSuffixList) %>;

Categories