Access database and use the data in Javascript

Hi all,

I have been learning Javascript and am creating a simple game, but now I want to start using data from a database table but after research, I’m confused about how to go about it. To make things easier to understand:

I have a simple game where a random sentence from a song is displayed together with three buttons showing artist’s names. The user then can click one of the buttons to see if they are correct or not.

I can do this in Javascript using variables and arrays but the whole script is ‘self-contained’ (everything is set up in the script).

What I would like to do is pull the information from a table in the database allowing for many, many more songs/artists and use this data in the script, but I don’t know how to get the information from the database and use that information in Javascript.

I know how to retrieve and manipulate the data using PDO and PHP but I don’t know how to do the same with Javascript.

I have read that accessing the database directly using Javascript is a big no-no due to security issues so I’m guessing that I would need to retrieve the information using PHP and then passing the variables over?

How is this done? What is the best method for doing this?

TIA

Yes, because JS runs in the browser, it doesn’t have access to the database running on the server, so you need to use AJAX which is a combination of JS and PHP (or another server-side technology).

Assuming your JS runs in a web page, it’s simply not possible; anything running in the browser has only access to your server via public web interfaces. So you basically have to options: either you dump the entire data into the page when rendering it, or provide a dedicated endpoint which your JS can then access with AJAX.

Variant 1 would look something like this:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>My Game</title>
</head>
<body>
  ...
  <script>
    window.GAME_DATA=<?php echo json_encode($myData); ?>;
    // You can now use window.GAME_DATA
  </script>
</body>
</html>

Or with variant 2 you’d have a separate PHP script, say data.php:

<?php

// Query database, then just
echo json_encode($myData);

And on your page, you’d then request the data like so:

var xhr = new XMLHttpRequest()

xhr.onload = function () {
  var data = JSON.parse(this.responseText)

  // You can now use the data
  console.log(data)
}

xhr.open('GET', 'data.php')
xhr.send()
2 Likes

Also note that Microsoft warns that Office products including Access are not designed for use in a server and there are many potential problems. It might work and when it does not work you might have difficulty understanding why. It is likely safe to do it for learning purposes when you are the only user but be prepared to switch to a different database later. However if you get an error that is difficult to understand it might be due to the use of Access in a server environment.

@m3g4p0p Thank you for the explanation. Variant 2 seems the most logical to me so I’ll give that a go. I’ll read up more on AJAX as I only know bits and pieces about it. But I know which way I’m heading now which is cool. Is this how it’s done on most sites? If so, it seems strange that something that’s used so much isn’t made simpler. Either that or I don’t know enough yet to realise that this is easier (the most likely!).

@SamuelCalifornia I think I confused the issue by using ‘Access database’ in the title. I won’t be using anything Microsoft.

2 Likes

Yes I was confused.

It is typical for web pages to process postbacks and update the page from that. For example How to handel postback event in php - PHP - The SitePoint Forums. That is probably the oldest way to do it but if it can satisfy requirements then it could be easier.

Depending on your specific needs, that may be all you need to actually get the data from the database.
On page load, the server-side (PHP/PDO) can get the data for the relevant questions and answers, maybe format it into JSON, and write it into the (java)script on the page.
Then javascript can access that data, without further calls to the database. This is fine if it’s only a light-hearted/fun quiz, where it does not matter if the player can cheat and find answers in the source code.

So how is Javascript secured then if everything is available in the source code? That sounds like it makes it mostly redundant (obviously it’s not, but I never really thought about whether the variables would be available to view from the source code).

It is not. That is a significant advantage of server-side programming.

I do not understand what you are trying to say there.

Have you read anything saying it IS secure? Anything front-end related (HTML/CSS/Javascript) can be viewed by anyone. Even if you uglify the Javascript or obfuscate it.

Javascript is an addon. You can do stuff like validate input, but yes, you’d need to also double check that server-side as well because anyone can easily just disable Javascript to bypass anything you are doing.

This post is the first instance where I’ve seen that it’s insecure. I’ve done online courses, but none of them have mentioned anything about security. I did assume (I know. Mother of all…) that as it’s so popular, security would be one of the main features of it.

What then, should I be using if I want more security?

Javascript should never be assumed to be secure so you need to rely on backend processing instead.

So e.g. for forms, if you want to validate user input…yes, Javascript can do it, but it’s not secure. However, it’s useful for those with Javascript enabled, or those who want enhanced website experience, to not need a refresh to tell them that “X is not valid input”. But it should always be supplemented with backend code which also validates the input. Javascript is to enhance user experience.

Hopefully that example was a helpful one :slight_smile: .

2 Likes

That is helpful!

It helps with narrowing down what to look for to complete the tasks I am working on (I have a lot of projects on the go). It also gives me an idea which direction I want to take. I’m certainly more of a back-end person as although I know the code, front-end is not something I enjoy doing from a design point of view. I can get a website working as I want it but as soon as it comes to making it look ‘nice’, I tend to get frustrated and then go onto something else. Hence the many projects :laughing:

As mentoned, the client side stuff isn’t secure. That’s why I mentioned, if it’s just a “fun” quiz, my soluton could work.
For something more serious, like a quiz with cash prizes, or an exam to gain an official qualification, you would need a solution that would secure the correct answers against mis-use.

My suggestion would securely access the database via server side to get the data for questions, answers and correct answers for the current page, but then place that data in client side code, out of plain sight. But anyone with a bit of know-how could, cheat and view the source code to see the correct answer.

This doesn;t necessarily make the javascript redundant. It is still there to drive the interactivity of the quiz, which is its true purpose.

If you did need some level of security for the answers, so they could not be found until after the player gives an answer, then you would need ajax to get them, without needing any page refresh.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.