Search code examples
phpjavascriptmysqlphpmyadminimpactjs

Runs php code from JavaScript in impact engine


I have created a game in using impact game engine called Staroids.

I have created a database to store the highscores.

I have done what it says on this previous answer and looked at a few other solutions, but it doesn't seem to work!

I am trying to run a php file which contains the following code:

<?php

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

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

?>

Here is the code that I run in the JavaScript file:

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

It comes up with the following error in console when it reaches this code:

Uncaught ReferenceError: $ is not defined 

Solution

  • I solved it with the help from the comments above and using a lot of trial and error, here is the working code:

    <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script>
    //make sure you run this otherwise the $post request wont work!
    

    Then where in the JavaScript function where I wanted to run the code I put:

    $.post('register.php', {score: this.score}, function(){}).error(function(){
        alert('error... ohh no!');
    });
    //this runs the php file parsing through the score variable
    

    Here is the PHP code which I then run to add the parsed through variable to the table in the database:

    <?php
    
        $score = $_POST['score'];
        mysql_connect("localhost", "root", "password");
        mysql_select_db("staroids");
        mysql_query("INSERT INTO scores (score) VALUES ('$score')");
    
    ?>