Boolean Switch - MySQL / PHP / AJAX

  • Tumult Hype - January 2, 2018

This HYPE project contains a simple Boolean Switch that changes a MySQL database entry via PHP using jQuery Ajax calls and then updates HYPE accordingly.

This guide is designed for those who are already familiar with PHP and MySQL Databases.


For those of you who want to just play with the files jump to the bottom of this page and click the "Download Files" button.

For a more detailed explaination of what is going on please read on. The Hype file contain two JS functions and 3 PHP files, the code for each is outlined below.

On the root timeline we use "On Scene Load" to run the following function():

Function projectSetup(hypeDocument, element, event) {

  BooleanSwitch_Instance = hypeDocument.getSymbolInstanceById("BooleanSwitch"); // Returns the symbolInstance for the symbol BooleanSwitchwith to the specified id.
	
  // In order to get current database value of the Boolean for the swith we need to query the database
  // We do this by making an Jquery Ajax call to the PHP file - The jQuery Library is loaded in the Head HTML
  $.ajax({ 
    type: "POST",
    url: "${resourcesFolderName}/BooleanSwitch.php",
    dataType : "json",
    success:function(result) {
	  		
      switchState = result; // The variable switchState is set via the PHP file thants queried the MySql Database
			
      // Move the Timeline position of BooleanSwitch Symbol depending on the Boolean setting - 0 or 1
      if (switchState == 0){ // If The button is Off
        BooleanSwitch_Instance.goToTimeInTimelineNamed(0, "Main Timeline"); // Show Switch as Off
      } else { // If The button is Off
        BooleanSwitch_Instance.goToTimeInTimelineNamed(0.5, "Main Timeline"); // Show Switch as On
    }
      hypeDocument.getElementById("booleanEntry").innerHTML = switchState; // Show database entry boolean number under the button
			
      window.switchState = switchState; // Set the Global variable of switchState
			
    },error : function () {
      alert("Cannot Find Value from database");
    }
  });
	
}

Then on the Button Symbol "On Mouse Click":


function changeBoolean(hypeDocument, element, event) {
	
  // Lets write the new value to the database.
  var switchState = window.switchState; // Set local varaible from global variable window.switchState
	
  // In order to change the database entry for the boolean we need to make a new ajax query to update the database
  $.ajax({ 
    data: { "switchState" : switchState},
    type: "POST",
    url: "${resourcesFolderName}/BooleanSwitcher.php",
    success:function(result) {
      window.switchState = result; // Reset the Global Variable to the new value
	  		
      // So we can be sure that the database has changed we can query it again
      $.ajax({ 
        type: "POST",
        url: "${resourcesFolderName}/BooleanSwitch.php",
        dataType : "json",
        success:function(result) {
          switchState = result; // Set this Variable via MySql Database
	  				
          // If the change has been succesfull then we animate the button
          if (result == 1){ // If The button is On
            BooleanSwitch_Instance.startTimelineNamed("Main Timeline", hypeDocument.kDirectionForward); // Animate the timeline of the BooleanSwitch to the On position
          } else { // If The button is Off
            BooleanSwitch_Instance.startTimelineNamed("Main Timeline", hypeDocument.kDirectionReverse); // Animate the timeline of the BooleanSwitch to the Off position
          }
			
          hypeDocument.getElementById("booleanEntry").innerHTML = result; // Show updated database entry boolean number under the button
		
        },error : function () {
          alert("Cannot Find Value from databases");
        }
      });
    }
  });
	
}

 

Thats it for the Hype File, these two js fuctions make the query to the following external PHP files of which there are 3. The first is to make the database connection, this would need to be changed to your prefered method and database details. This particular method uses a class file and PDO.

<?php
class Database {
	
	
	private $host      = "localhost";
	private $db_name   = "HYPE_Templates";
	private $username  = "root";
	private $password  = "";
	
	public $dbh;
     
	public function dbConnection() {
	
		$this->dbh = null;
		try {
			$this->dbh = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
			$this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);	
    }
		catch(PDOException $exception) {
			echo "Connection error: " . $exception->getMessage();
		}
    return $this->dbh;
    
  }
  
}

Once you have established to connection we can we need to get the data to and from the database.

To query the database and echo the result back to HYPE we use the following PHP:

<?php
error_reporting(E_ALL); // PHP Error Reporting
ini_set("display_errors", 1);  // PHP Error Reporting

// Set up a class file for the Database
require_once("db.class.php");
$database = new Database();
$dbh = $database->dbConnection();

$stmt = $dbh->prepare("SELECT SWITCHSTATE FROM booleanSwitch WHERE ID=:id ") or die("No such switch");
$stmt->execute(array(":id"=>1));
$getSwitch = $stmt->fetch(PDO::FETCH_ASSOC);
$SWITCHSTATE = $getSwitch["SWITCHSTATE"];

echo json_encode($SWITCHSTATE);

Then to update the database on button click from HYPE:

<?php
error_reporting(E_ALL); // PHP Error Reporting
ini_set("display_errors", 1);  // PHP Error Reporting

// Set up a class file for the Database
require_once("db.class.php");
$database = new Database();
$dbh = $database->dbConnection();

$SWITCHSTATE = $_POST["switchState"];

if ($SWITCHSTATE == 1) {
	$SWITCHSTATE = 0;
} else {
	$SWITCHSTATE = 1;
}

$dbh->query("UPDATE booleanSwitch SET SWITCHSTATE="$SWITCHSTATE" WHERE ID = 1");

echo json_encode($SWITCHSTATE);

 

Please download the working files from below which includes an example MySQL database with a single entry.

Download Files

Comments