Adding new words to the game - javascript

In my spelling game new words will be added all the time so there is always a fresh selection of words to spell.
Each word added to the game has a "src" to an image and a sound that will prompts the user into getting the spelling correct in gameplay.
When I have completed making the game, the job of adding the new words in is down to one of my colleagues. This means he will have to add a link for the pic and audio as well as the word.
As they have little knowledge with this sort of thing I want to make it as easy as possible for him to add the images and sounds when adding the words I want to create a default path to a shared location where he will store all this stuff.
This way he can just type in "bug" for the word, ".bug-pic" for the picture and ".bug-audio" for the sound making it simple for him to add into the HTML.
Is this the best way to do it?
What would be the simplest way for them to input these things?
Here is how I store the word, sound and image at the moment...
<ul style="display:none;" id="wordlist">
<li data-word="mum" data-audio="file:///C:/smilburn/AudioClips/mum.wav" data-pic="http://www.clker.com/cliparts/5/e/7/f/1195445022768793934Gerald_G_Lady_Face_Cartoon_1.svg.med.png"></li>
<li data-word="cat" data-audio="file:///C:/smilburn/AudioClips/cat.wav" data-pic="http://www.clker.com/cliparts/c/9/9/5/119543969236915703Gerald_G_Cartoon_Cat_Face.svg.med.png"></li>
<li data-word="dog" data-audio="file:///C:/smilburn/AudioClips/dog.wav" data-pic="http://www.clker.com/cliparts/e/9/4/1/1195440435939167766Gerald_G_Dog_Face_Cartoon_-_World_Label_1.svg.med.png"></li>
<li data-word="bug" data-audio="file:///C:/smilburn/AudioClips/bug.wav" data-pic="http://www.clker.com/cliparts/4/b/4/2/1216180545881311858laurent_scarabe.svg.med.png"></li>
<li data-word="rat" data-audio="file:///C:/smilburn/AudioClips/rat.wav" data-pic="http://www.clker.com/cliparts/C/j/X/e/k/D/mouse-md.png"></li>
<li data-word="dad" data-audio="file:///C:/smilburn/AudioClips/dad.wav" data-pic="http://www.clker.com/cliparts/H/I/n/C/p/Z/bald-man-face-with-a-mustache-md.png"></li>
</ul>
THANKS

I'm going to break your mold a bit here, and suggest something that looks simple enough for me in the long run (at least, simpler than what you have here).
The problems with using HTML markup to store your words is that:
it's HTML --- the browser will have to parse this, but then not display it because you've got the <ul> element as display:none (it's just sort of wasted effort), and
XML (or HTML, whichever) is pretty bloated, in the sense that there's a lot of text needed to represent information. If you're going for a spelling game, I'm assuming that you'll have hundreds, or thousands of such words, and the HTML representation for your words will be a huge crapload of bandwidth bloat.
So! Here's what I'd suggest:
// create an external JS file to store your words,
// let's say, [words.js].
// then let's just store your words in an array
var words = [
{ word : "foo" , audio : "file:///C:/smilburn/AudioClips/foo.wav", pic : "http://www.clker.com/cliparts/5/e/7/f/1195445022768793934Gerald_G_Lady_Face_Cartoon_1.svg.med.png" },
{ word : "bar" , audio : "file:///C:/smilburn/AudioClips/bar.wav", pic : "http://www.clker.com/cliparts/5/e/7/f/1195445022768793934Gerald_G_Lady_Face_Cartoon_1.svg.med.png" },
{ word : "mum" , audio : "file:///C:/smilburn/AudioClips/mum.wav", pic : "http://www.clker.com/cliparts/5/e/7/f/1195445022768793934Gerald_G_Lady_Face_Cartoon_1.svg.med.png" }
];
It's just a plain Javascript array that holds a collection of Javascript objects. Each object has three properties: word, audio and pic.
Load that file into your page, and have a script read from that. It'll be much easier and faster to traverse, use and apply to your page. Reading to and fro a JS object is generally faster than having to parse and read the same information from the DOM.
Additionally, the markup is more compact, and you're not [misusing] HTML DOM for something it (arguably) wasn't supposed to be doing.
Thirdly, it's much more organized and cleaner to look at than HTML markup, and I imagine that that will be much easier for your colleagues to update and adapt to.
Lastly, one nice thing about this approach is how easy it is to write your code into modules, so you can work with stuff like expansions / word packs easier:
// something like this can work:
// [words.js]
var words = [
// some base words
{ word : "foo", audio : "foo.wmv", pic : "foo.pic" }
// ...
];
// [words.animals.js]
(function () {
// do not do anything if the base [words.js] isn't loaded
if (!words) { return; }
// extend the base words
words = words.concat([
// new animal words!
{ word : "dog", audio : "bark.wmv", pic : "brian.jpg" }
// ...
]);
})();
The idea being, you can load the words.js file into your game and it'll work perfectly. However, if the user would also like to add new words (say, words for animals) then they (you) can just load auxiliary files to augment your base words list.
This is much easier to do with JS objects than with HTML markup.
EDIT
If you really positively final-answer must have to use HTML, I recommend chopping off the data-word attribute off your <li> and just use it's text value instead.
<li data-audio="dog.wmv" data-pic="dog.jpg">dog</li>

I would recommend, that you simply store the info like this:
<li data-word="mum" data-audio="mum.wav" data-pic="/5/e/7/f/1195445022768793934Gerald_G_Lady_Face_Cartoon_1.svg.med.png"></li>
After reading your jsFiddle i would recommend you crate a playAudio function like this:
function playAudioFile (audioFileName) {
audioFileName = "http://www.wav-sounds.com/cartoon/" + audioFile;
$("#mysoundclip").attr('src', audioFileName);
}
after that you can replace this:
$("#mysoundclip").attr('src', listOfWords[rndWord].audio);
audio.play();
by something like this:
playAudioFile(listOfWords[rndWord].audio);

You have to use attr() to store images in default location. Here they explain the default location to store images.

You might want to consider what server side technology you'll have available too.
If you have to add the options through html, then what you can probably do in that portion of the page, is have the html elements generated dynamically by the server.
'ASP Classic example
<%
set fs = server.createObject("scripting.filesystem")
set folder = fs.getFolder("your path here")
for each file in folder.getFiles("*.wav")
strWord = left(file.name, length(file.name)-4)
%><li data-word="cat"
data-audio="path/to/folder/<%=strWord%>.wav"
data-pic="path/to/folder/<%=strWord%>.png"></li>
<%
next
%>
This is just an asp classic example, I'm sure you'll find others out there specific to the platform your using.
But basically... you have to have SOMETHING on the server tell the output page what is available if you want to make it a drop-in-and-go operation. Otherwise you might as well be doing the html as you have been. Technology isn't always going to replace plain ol data entry.

Well, in my opinion, you can use a database, a server side script and a form for your colleague. Create a form which he will use to upload the information to the server and store the paths into the database.
The form:
<form method="POST" action="myscript.php" enctype="multipart/form-data">
<p>Word:<input type="text" name="my-word" id="my_word"></p>
<p>Audio:<input type="file" name="audio" id="my_audio" /></p>
<p>Picture:<input type="file" name="picture" id="my_picture" /></p>
<p><input type="submit" name="submit" value="Submit" /></p>
</form>
The script:
<?php
$conn = mysql_connect("your_host", "your_user", "your_pass") or die (mysql_error());
mysql_select_db("your_database", $conn) or die (mysql_error());
if( ( $_FILES[ 'audio' ][ 'error' ] > 0 ) || ( $_FILES[ 'picture' ][ 'error' ] ) ){
echo "Error" . "<br />";
}
else{
move_uploaded_file($_FILES["audio"]["tmp_name"], "your/upload/directory/for/audio/" . $_FILES["audio"]["name"]);
move_uploaded_file($_FILES["picture"]["tmp_name"], "your/upload/directory/for/images/" . $_FILES["file"]["name"]);
mysql_query( 'INSERT INTO your_table ( word, audio, image ) values ( "' . $_POST[ 'word' ] . '", "' . $_FILES[ 'audio' ][ 'name' ] . '", "' . $_FILES[ 'picture' ][ 'name' ] . '" )', $conn );
}
?>
Of course your database should have a table which stores those 3 values plus some id.

I think you can add more entries to a list like this in javascript:
function addLI(id){
var Parent = document.getElementById(id);
var NewLI = document.createElement("LI");
NewLI.innerHTML = "this is a test";
Parent.appendChild(NewLI);
}
which I found from here: http://bytes.com/topic/javascript/answers/520885-add-new-list-item
I recommend having input fields with the name, location and picture for your friend to add more entries with, then use something like this js function to add a new child entry.

If you have access to a server with PHP, I would suggest putting all them items in a array and then looping through them.
I have written an example here:
<?php
$wordsArray = array(
array('word'=> 'randomword' , 'audio' => 'test.mp3', 'picture' =>'pic.jpg'),
array('word'=> 'randomword2' , 'audio' => 'test2.mp3', 'picture' =>'pic2.jpg')
);
$html = '';
foreach($wordsArray as $word){
$html .= '<li data-word="'.$word['word'].'" data-audio="'.$word['audio'].'" data-pic="'.$word['picture'].'"></li>';
}
?>
<html>
<head>
<title></title>
</head>
<body>
<ul>
<?php echo $html; ?>
</ul>
</body>
</html>

Related

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?

passing data to a new html window

Sorry guys but this is a little broad, I've searched but there are a few things coming up but I wanted a direct answer for my question.
First I am a mechanic at a truck dealership in Dallas, TX. I am writing a web based application that will make it easier for me to organize all my jobs. I'm using this project to teach myself HTML, PHP, PDO, javascript ect. Right now I'm in design and organization phase meaning I'm getting everything I want figured out so when I start the hard coding I know ahead of time where to go.
Now when a tech logs in they will be brought to the tech landing page. I'm going to have a php script that will retrieve all the 20 most recent "active" Ro's (repair orders) assigned to that particular tech. A table will display summary info on a line at the end of each line there will be a button (or I might make the RO # clickable not sure yet.
My question is what is the best way to open a new window and pass the RO# of the clicked option so scripts on the new page can begin populating the detailed RO information from the database??
I'm not necessarily looking for the code but something I can search to narrow down my options.
Thanks
There are a few ways you could do this.
A simple link with querystring:
-------------------------------
<a href='/repairs.php?mechanic=bob' target='_blank'>Bob's Repair Orders</a>
<a href='/repairs.php?mechanic=curly' target='_blank'>Curly's Repair Orders</a>
A simple link with a javascript function:
-----------------------------------------
<a href='#' onclick='getRepairs('bob')'>Bob's Repair Orders</a>
<a href='#' onclick='getRepairs('curly')'>Bob's Repair Orders</a>
javascript:
function getRepairs(name){
window.open('/repairs.php?mechanic='+name );
}
You have 2 options to do this:
(Recommended) Pass RO# (id) in address page.php?id=1001 and fetch id using get method
on new page. It will be a full page with all bars and every thing
enabled.
Collect data in a DIV and open a new page and populate data to it.
Code for Option 1:
Page 1: ROlist.php (Which Contains list of 20 ROs)
RO#1001
Page 2: ROdetails.php (Which will open only id based details)
<?php
$ROid=$_GET['id'];
$result=mysql_query("SELECT * FROM table where id='$ROid'");
if($result)
{
while($list=mysql_fetch_array($result))
{
echo $list['Id'];
echo $list['clientName'];
echo $list['foo'];
echo $list['bar'];
}}
?>
You can call the following in JavaScript:
window.open("<yourUrl to open>?ro=someValue")
and pass the ro value to the new window as a query paramter (?ro=someValue where someValue will be replaced by the value to pass over and is the url of the page to load in the new window).
In the new window you can retrieve it using:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var ro = getParameterByName('ro')
Note: getParameterByName is from How can I get query string values in JavaScript?
Use a GET parameter : index.php?ro_id=1
Now this URL should be generated through PHP, where 1 is a variable and is the RO#.
Other solutions told how to open it in a new window, you don't need JS to read $_GET though.
Like what Uchiha comment is suggesting, you can put your RO# into a link.
In your html you can put something like this:
<a target="_blank" href="ro_table.php?ro_number=RO number here"> RO# </a>
and in your ro_table.php or any php file you prefer to receive the RO# you can get the RO# by: $_GET["ro_number"] and use that to your database query.

Can I read the input from a HTML form and save it at at a specific position in TXT file?

I used this as reference:
Can I save input from form to .txt in HTML, using JAVASCRIPT/jQuery, and then use it?
Can I save input from form to .txt in HTML, using JAVASCRIPT/jQuery, and then use it?. But that is intended for client side and I want server side.
I have a TXT file with this content:
PAGE=1
until [ $PAGE -gt 9 ]; do
wget "http://www.example.com/INPUT-WORD-HERE/page_0"$PAGE".jpg"
let PAGE+=1
done
PAGE=10
until [ $PAGE -gt 99 ]; do
wget "http://www.example.com/INPUT-WORD-HERE/page_"$PAGE".jpg"
let PAGE+=1
done
Is it possible for me to read the input from a HTML form and save it at a specific position in this TXT file (hosting). The specific position is INPUT-WORD-HERE. So, the idea would be to replace all the INPUT-WORD-HERE with the HTML input.
So from what you describe, this is what should be done (I used PHP for the code as you tagged your question with it):
Open your batch file as a string.
$fileTXT = file_get_contents($path_to_your_file, FILE_USE_INCLUDE_PATH);
(Replace $path_to_your_file with the relative path to the file that you want to update)
Replace all the instances of INPUT-WORD-HERE with the new input:
$fileTXT = str_replace("INPUT-WORD-HERE", $textToReplace, $fileTXT);
But it is not that simple. This is a bit trickier than what it seems initially, as INPUT-WORD-HERE will not be the same text from one time to another. We need to create a generic script that will replace whatever the value is:
$pos1 = strpos($fileTXT, "http://www.example.com/");
$textFrom = substr($fileTXT, $pos1+23, strpos($fileTXT, "/", $pos1 + 23) - $pos1 - 23);
$fileTXT = str_replace("http://www.example.com/" . $textFrom . "/", "http://www.example.com/" . $textTo . "/", $fileTXT);
I replace the whole URL, to avoid possible problems if the previous INPUT-WORD-HERE value matched a different text in the file (e.g.: "example" or "PAGE")
Save the file.
file_put_contents($path_to_your_file, $fileTXT);
The final code would look like:
<?php
// here the relative path to your batch file
$filename = "myfile.txt";
// replace $_GET["txt"] for the name of the input that will have the new value. You can use $_POST too
$textTo = $_GET["txt"];
// read the content of the file into a string
$fileTXT = file_get_contents($filename, FILE_USE_INCLUDE_PATH);
// get the word to be replace from the URL (23 is the length of "http://www.example.com/", you'll need to change that number to fit the URL that you place there)
$pos1 = strpos($fileTXT, "http://www.example.com/");
$textFrom = substr($fileTXT, $pos1+23, strpos($fileTXT, "/", $pos1 + 23) - $pos1 - 23);
$fileTXT = str_replace("http://www.example.com/" . $textFrom . "/", "http://www.example.com/" . $textTo . "/", $fileTXT);
// overwrite the content of the file
file_put_contents($filename, $fileTXT);
As I specified in the comments, this solution presents some dangers and should not be used with common users (you said it was Ok, as it was only for you). If you change it so common users can access it, you should preprocess and sanitize the input.
As requested by the user, this is a simple example of how the HTML form could be:
<form method="get" action="YOUR_PHP_FILE_WITH_THE_ABOVE_CODE">
<label for="txt">
Write here the new name:
<input type="text" name="txt" id="txt" />
</label>
<input type="submit" value="Make Changes" />
</form>
You just need to make sure that the text input has the same name as the parameter that you read in the $_GET (or in the $_POST, but then you'd need to change the form to method="post").

How to get the hostname without TLD from a url

I'm in the process of creating a website. Every time the user uploads a link, I need to save the link and its name/value. This is hard to explain.
Here's what I'm trying to say. Lets say the user pastes a link in an input. https://www.google.com/ The link needs to be saved in an XML file. When I call the link:
I want to also call the name:
Google
I want to extract "google" from "https://www.google.com/"
I know I could use:
str_replace(' ', '', )
But not all links are the same.
I know this code won't work because I already tried it.
I know the right code is simple probably 3 lines. So I would really appreciate it if you guys could help me out.
Thank you.
parse the url. get the host part and explode the string with a dot (.) as delimiter.
$url="https://google.com/";
$parts = parse_url($url);
$parts=explode('.',$parts['host']);
echo $parts[0]; // parts[1] contains com, parts[0] contains google
To work with urls that contain 'www' you might do something like this. Mind that this is not working with subdomains.
echo getName("http://www.google.com"); //prints google
function getName($url){
$parts = parse_url($url);
$parts=explode('.',$parts['host']);
$data=$parts[0]=="www"?$parts[1]:$parts[0];
return $data;
}
To work with every url, including subdomains I think it is more easy to use a regex. I adapted the function from this question to fulfil your needs.
function getName($url){
$pieces = parse_url($url);
$domain = isset($pieces['host']) ? $pieces['host'] : '';
if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) {
return explode('.',$regs['domain'])[0];
}
return false;
}

Posting data via js/jQuery

I am really new to Javascript and its many brilliant libraries, I find even the most simple scripts hard to perform.
I do want to learn this language, because it would be powerful for creating client websites, however at the moment I am trying to do something relatively simple, this is to flag a personal message on my site. There are many messages in a big list, and what I am looking at doing is when the user clicks the "Flag PM" image, it will run flag.php in the background which will change the flag field in MySQL from 0 to 1.
This script is all dependant on one field, that is id so I can run this through the database. Anyway, here is my code;
flag.php
require('_inc/_core/core.php'); // inc core_funcs for sql & clean
$pm_id = clean($_POST['p_id']); // create new variable, clean the post
echo "The ID for the PM is " . $pm_id;
mysql_query("UPDATE `messages` SET `flag_status` = 1 WHERE `id` = {$pm_id}"); // update the db
JS/jQuery
// Flag a Personal Message
$("#flagPM").submit(function(event) {
event.preventDefault();
$.post("flag.php", { p_id: pm_id } );
alert(event);
});
HTML handling the form
<form action="#" id="flagPM"><input type="hidden" id="pm_id" value="$id" />
<input type="submit" class="submit" value="FLAG" /></form>
So there is a hidden input field named pm_id that contains what I want posted.
Would really appreciate some help, the Javascript is being run from an independent file that is two directory's up from flag.php
Thank you
the Javascript is being run from an independent file that is two
directory's up from flag.php
In that case simply doing:
$.post("flag.php", { id: id } );
wont reach the flag.php file, you need to specify correct path including folder names that you mentioned:
$.post("folder1/folder2/flag.php", { id: id } );
By the way, you should use a callback for the $.post function to know what message is returned by flag.php:
$.post("flag.php", { id: id }, function(data){
alert(data);
} );
From your flag.php, make sure to echo something so that you get that response in your ajax handler:
// your other code here, such as query, etc
echo 'whatever...';

Categories

Resources