Reading from a text file into HTML - html

I want to make a small html based game for a school project. I would like to be able to extract data from a text file, then insert if necessary in order to save data. So my question is:
What programming language can i use in order to read from a .txt file into a HTML page?
Thanks in advance for any help you are able to provide.

My suggestion would be php. There are dozens of methods to achieve this. Note, however, that this task will be much easier to accomplish if your text file is on the same domain as the code. This is best for single levels that dont change.
Php
In php, you could use
$file = fopen('pathtofile.txt', r);
Note that the second parameter, r, signifies that the file should be readable. Use w if you want to write to the file.
There are a lot of tutorials on google for this.
Ajax
If you'd prefer not to use php, Ajax is also available to you via javascript. This method is best if you need to change files while the game is running, ie loading new levels.
$.ajax({
method: 'get',
path: 'pathtofile.txt',
success: function(data){
//level info is in **data**
},
error: function(x, h, r){
// this will display error info, ie file does not exist
}
})
The code above most likely won't work, it is intended as a demo. Again, there are plenty of examples for this on google.
Have fun and happy coding.

Related

What's the lightest way to add the smallest amount of dynamics to a static HTML site?

I have a personal website that's all static html.
It works perfectly for my needs, except for one tiny thing.
I want to dynamically change a single word on a single page: the name of the current map for a game server I'm running.
I can easily run a cron job to dump the name of the map into a file in the site's html directory, call it mapname.txt. This file contains a single line of text, the name of the map.
How would I update, say, game.html to include this map name?
I would very strongly prefer to not pull in some massive framework, or something like php or javascript to accomplish this.
I want the lightest weight solution possible. Using sed is an option, although definitely a hacky one. What's the tiniest step up from static html?
If you say "dynamically", do you mean:
If the information changes ...
A) the user should see it after they have re-loaded the page?
B) the page should update without the need to reload?
For A, you can use PHP (or any other language your server supports) to read the data from the file and print it into the web page. This will happen on server side.
For B, you can use JS that queries the file and updates the HTML. This will happen on client side.
To change text there are a few way though only two appropriate methods.
First is using textContent:
document.getElementById('example').textContent = 'some example text';
Secondly is the older nodeValue however it's a bit more tricky since you have to specify the exact textNode (e.g. .firstChild):
document.getElementById('example').firstChild.nodevalue = 'some example text';
You're 100% on the mark about not using frameworks or libraries, almost everything exists without the suck.
I'm not going to test this though this is a very stripped down version of my ajax function from my web platform. Some people might scream about the Fetch API however the syntax is an absolute mess. I recommend figuring out how to standardize this function so you can use it for everything instead of making copies of the code for every instance. Mine supports both GET and POST requests.
function ajax(method, url, param_id_container_pos, id_container)
{
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.timeout = 8000;
xhr.open(method,url,true);
xhr.send(null);
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4)
{
if (xhr.getResponseHeader('content-type'))
{
var type = xhr.getResponseHeader('content-type').split('/')[1];
if (type.indexOf(';') >- 1) {type = type.split(';')[0];}
}
else {var type = 'xml';}//Best guess for now.
console.log(type,xhr);
console.log(xhr.responseText);
//console.log(type,xhr.responseXML);
//document.getElementById('example').textContent = xhr.responseText;
}
}
}
You're also going to have to ensure that the url is set to an absolute path. I use path variable in my platform (see my profile for the link, wildly clean and organized code).
There are plenty of ways to make this function reusable and I highly recommend doing that. For now use the last non-curley-bracket line to update your line of text.

Simple function to read file from an URL to a string buffer ( C++ / MQL{4|5} using WinInet.dll )

I am looking for a simple function which is able to read a text or binary file from the internet into a string variable.
It´s unbelievable that I could not find anything in the web, just low level descriptions of all the WinInet functions and useless samples, that do not work at all, at the MQL-forums.
What I need is a function like:
string buffer = ReadTextFileFromWeb( "www.myurl.net/textfile.txt" );
No more, no less. I am not very familiar with internet programming stuff at all, but I am sure there is anybody out there who is able to present the reason just like that.
The code will be used in MQL4/MQL5. I know that there is already a WebRequest() function which works, but it is restricted to expert advisors and cannot be used in Custom Indicator type of code.
I need this solution to load data into a custom indicator.
Go get this on github https://github.com/sergeylukin/mql4-http
//For MT4 Add HTTP Access
#include <mql4-http.mqh>
string URLr = "www.myurl.net/textfile.txt";
Print("URLr return is: ", URLr);
For MT5 you are on your own.
The above dose not have the issues that WebRequest() has. Or I have not seen it have any issues. I use it all the time in a lot of EA and never had a chart lockup or have a issue.

What's the proper way to store Data for an AngularJS driven learning page

I am building a webpage for learning. Actually doing the page is the main goal, if it works well it would only be a bonus since i will most likely be the only person using it.
That being said i am using Angular Objects that hold a lot of informations, like:
Semester - Subcategory - Question - List of answers as objects with "true"/ "false" properties for multi choice and the answer itself ect.
Since i will be doing the whole sorting / filtering with angular i wonder if i really need SQL or if a XML file would be superior.
With SQL saving is my main issue here. PHP seems to butcher arrays into a string with the value "array". If i use json_encode it saves correctly, but on GET it stops working since i have to rebuild the whole data structure with " and ' about everywhere.
With XML it really looks like angular just is not build for that. I have found some outdated tutorials that did not even have a working example.
So i guess my question here is:
Do i either go for SQL, putting up with multiple tables. Splitting my objects into several columns with optional values all over the place, while also rebuilding the whole thing on load?
Or do i use XML, since i would only use the DB to GET the whole thing anyways?
Both approaches have been tested by me and work, somewhat. Both would need quite a lot of further digging, reading and trying. I don't have the spare time to do both routes. Which one is the better one to go for in this particular use case?
This is ofcourse a personal preference but I always try to avoid XML. The JSON format is alot lean and meaner and it's way easier to work with in web applications.
In fact I would suggest to start with some static JSON files until you're finished with giving your website some structure. You can generate them manually, use some generator tools (like http://www.mockaroo.com/) or build them by using some simple javascript (JSON.stringify is your friend). You can then use this data quite easily by using the $http service:
$http.get('my-data.json')
.then(function(response) {
$scope.myData = response.data;
});
This is actually the approach my teams take when building large enterprise applications. We mock all data resources and replace them with the real thing when we (or the customer) are happy with the progress.
Using a JSON-File should be sufficient. You can store all the needed objects in it and change it easily. With the following code you can load the data within JavaScript
function loadJSON(path, success, error) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
if (success)
success(JSONH.parse(xhr.responseText));
} else {
if (error)
error(xhr);
}
}
};
xhr.open("GET", path, true);
xhr.send();
}
usage
loadJSON('data.json',//relative path
function (data) {//success function
$scope.questions = question;
$scope.$apply();
},
function (xhr) {//error function
console.error(xhr);
}
);

Changing html on a view based on if get parameter is set on Codeigniter

Before I used Codeigniter I had a page show certain html as long as the url had no get parameters and then have some of the html be replaced by another as soon as something like this is set in the url:
localhost/signup.php?success
Now my question is, what is the best way to do this in Codeigniter? Would I have to use one of those parameters on the controller's function (which I still can't get my head around)? And if so, how? Or if I just had php logic in the view like I used to do in plain PHP, what would I check for if not a get parameter? Thanks.
Too many ways to achieve this certain thing.
routes.php
extending controller and using constructor so you apply rules for every extended controller
flashdata
Before you start please read up on frameworks watch some video tutorials on how to make simple blog system etc. I myself wouldn't just jump in to concept, study up.
I mentioned flashdata and that is how you do things done (success, alert, warning bars).
By default, GET parameters are not enabled or useful in codeigniter, but URI segments work the same way. So...
If you had a controller called, signup.php and a function inside it called success, you could link to that with:
localhost/signup/success
then if you loaded the URL helper, which I always do in config/autoload.php or just with:
$this->load->helper('url');
You could say:
if($this->uri->segment(2) == 'success') {
//Show success message or load a view for it...
}else {
//The second URI segment is NOT 'success' so do something else...
}
But... codeigniter is just a framework for PHP. If it's possible in PHP, it's possible in codeigniter. You can simply go into the config/config.php file and enable query strings, but I would strongly suggest using URI segments and reading up on them as well as the URL helper.

What is the best way to make a configurable text elements for HTML5 App

I am doing a HTML5 app. Everything works well. The client suddenly requested that he needs to change error messages and text labels as he wish after completing the code, but without touching the HTML5. So I got two solutions in to my mind.
1 Use javascript variables
// Error Messages
var msg_authentication_failed = "The username or password is invalid. Please try again";
and use this variable as I wanted.
2 Use XML file (Or JSON)
<?xml version="1.0" encoding="ISO-8859-1"?>
<ErrorMessages>
<AuthenticationFail>The username or password is invalid. Please try again</AuthenticationFail>
</ErrorMessages>
Load XML file and set values using it's tag names.
However I feel that the 2nd solution is easy to maintain by the client but performance wise it's not good.
Is there any other possible way to get done this kind of requirement? Appreciate your suggestions.
I'm running a jQuery Mobile project which supports around 6 languages (from Europe) and what I did was simply maintaining the labels in a JSON string.
using the event pagebeforeshow I update the labels when showing form element's labels. If it is an error message, I wrote a custom function that can access the string based on the labelID.
More than XML, JSON is extremely easy to handle. I would suggest you to go ahead with it.