How Do I Run PHP Code from JavaScript in Impact Engine

I’m working on a little game project using the ImpactJS game engine, and I ran into something that initially stumped me connecting my game to a PHP backend to store high scores.

The game I created is called Staroids, and the goal was simple: save player high scores in a MySQL database. I thought this would be a walk in the park just slap a PHP file together and use $.post() to send the score,

Let me walk you through what I tried, what went wrong, how I fixed it, and how I added some extra functionality like fetching and displaying high scores.

The Original Code

PHP File – register.php

<?php
$connect = mysql_connect('localhost', 'root', 'password');
mysql_select_db('staroids', $connect);

$sql = 'INSERT INTO staroids (score) VALUES ("'.$_POST['score'].'")';
$result = mysql_query($sql);
?>

JavaScript in ImpactJS

$.post('scripts/register.php', {score: score}, function(){}).error(function(){
alert('error... ohh no!');
});

Looks reasonable, Well, when I ran it.

The Error I Got

Uncaught ReferenceError: $ is not defined

Explanation:

This error is actually super common. It means jQuery isn’t loaded. The $ symbol is shorthand for jQuery, so if the browser doesn’t recognize it, that means the jQuery library wasn’t included before the script that used it.

How I Fix the Error

Load jQuery Properly

I made sure to include this line in my HTML <head> or right before my game scripts:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

Then I loaded my ImpactJS game after that:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="lib/game/main.js"></script>

Boom! The $ symbol now worked as expected.

But Then I Notice More Problem

The PHP code itself was pretty outdated and insecure:

  • I was using the old mysql_* functions deprecated in PHP 7+.
  • I had no error handling, so I had no clue if the query failed.
  • I wasn’t sanitizing the input a big no-no when it comes to SQL injection.

Update and Secure PHP Code

I rewrote the PHP using mysqli and prepared statements for security:

<?php
$connect = new mysqli('localhost', 'root', 'password', 'staroids');

if ($connect->connect_error) {
die('Connection failed: ' . $connect->connect_error);
}

$score = $_POST['score'] ?? 0;
$stmt = $connect->prepare('INSERT INTO staroids (score) VALUES (?)');
$stmt->bind_param('i', $score);

if ($stmt->execute()) {
echo json_encode(['success' => true]);
} else {
echo json_encode(['success' => false, 'error' => $stmt->error]);
}

$stmt->close();
$connect->close();
?>

Now it’s safe, and it gives back a JSON response I can handle in JavaScript.

Updated JavaScript to Post Score

if (typeof $ !== 'undefined') {
$.post('scripts/register.php', { score: playerScore }, function(response){
const result = JSON.parse(response);
if (result.success) {
alert('Score submitted successfully!');
} else {
alert('Error: ' + result.error);
}
}).fail(function(jqXHR, textStatus, errorThrown){
alert('Request failed: ' + textStatus);
});
} else {
console.error('jQuery not loaded!');
}

This way, I get clear alerts on success or failure no more silent error.

Displaying Top Score in the Game

I wanted to show the top 10 scores to players. So I wrote another PHP file for that.

PHP File – get_scores.php

<?php
$connect = new mysqli('localhost', 'root', 'password', 'staroids');

if ($connect->connect_error) {
die('Connection failed: ' . $connect->connect_error);
}

$result = $connect->query("SELECT score FROM staroids ORDER BY score DESC LIMIT 10");
$scores = [];

while($row = $result->fetch_assoc()) {
$scores[] = $row;
}

echo json_encode($scores);

$connect->close();
?>

JavaScript to Fetch and Display Score

function fetchHighScores() {
$.get('scripts/get_scores.php', function(response){
const scores = JSON.parse(response);
console.log('Top Scores:', scores);

// You could also dynamically render these into the game UI
let scoreList = document.getElementById('score-list');
if (scoreList) {
scoreList.innerHTML = '';
scores.forEach((entry, index) => {
let li = document.createElement('li');
li.textContent = `#${index + 1}: ${entry.score}`;
scoreList.appendChild(li);
});
}
});
}

I even added a simple <ul id="score-list"></ul> in my game overlay so I could display them on the screen.

Final Thought

At first, I thought running PHP code from JavaScript would be simple and it kind of is but only when everything is set up correctly. You need to load jQuery before using functions like $.post() or $.get(), and your PHP scripts should use secure practices like mysqli with prepared statements. Returning JSON makes the communication between frontend and backend much smoother, and checking responses in JavaScript helps with debugging. Once I sorted all that out, not only did I fix the issue, but I also added cool features like score submission and a live top 10 leaderboard.

Related blog posts