I am creating a Vocabulary section in my Website. There are various options like Idiom of the Day, Saying of the day, Word of the day etc. There are buttons for each option (see the attachment).
As of now, I have used “alert” dialog box to display the required information. For example, the code that implements Idiom of the day looks like
function idiom()
{
var retVal=confirm("About to display the idiom of the day. Press OK to continue");
if(retVal==true)
{
alert("to put on the backburner: \n\nIf things are put on the back burner, they are put on hold");
return true;
}
else
{
alert("Aborting the process.");
return false;
}
}
In the alert function call, I have written the Idiom and the meaning that needs to be displayed when the Idiom button is clicked.
Now, to improve upon this, I want to store all the idioms and their meaning in a file (as a symbol table consisting of two columns), then I want Javascript to randomly pick one row, assume the first column entry to be the idiom and the second column entry to be its meaning. Assuming this, Javascript must display the corresponding information.
For this, I require Javascript to be able to read a file. Could you suggest some functions, tutorials etc. that I can use for the same(specifically, I am stuck at “file operations and handling with Javascript” part). It is not necessary to provide me with the code, even a useful reference will work.
A snapshot of my website looks like: -
Where are you running the JavaScript? If in the browser then you need to do a call to the server to be able to have server side code read the file and return the results.
I am writing the HTML and Javascript codes in individual files putting all the images, CSS files etc in one folder. To test my code I go to that folder and open the corresponding file in Web Browser.
So from there JavaScript can’t access any files at all - the only way JavaScript can access files is via a call to the server and have the server read the file in.
Yes - that will provide you with a way to read a file from JavaScript by sending an XMLHttpRequest.
Whether you call the request directly or get jQuery to call it doesn’t matter as the call works the same whichever JavaScript code you use to generate the call.