3D Gallery with Great Artwork Imagine Logo with Three Colors Beach Cabin 3D Android Tablet with Different Screens Studio Apartment Red Figured Greek Vase on Blue Background Silver and Gold Flashlight Lake on Fire

JavaScript: Client-Server with JSON, PHP & MySQL

Page 21

Client-Server with JSON, PHP & MySQL

Introduction Tap: Requests Bison Information from a JSON Server. Tap: Requests Pronghorn Information from MySQL and JSON. Select an Animal from the Menu JSON Client-Server Code HTML Markup JavaScript PHP Examples Pages: JavaScript,JSON,MySQL: South Dakota Animals: Full Table Simple JSON Server Page JSON with MySQL Summary

Introduction

Learn to implement two JSON client-servers with JavaScript, PHP and MySQL. This page includes explanation, source code and examples. The examples display information about animals in South Dakota, in response to one tap of a button, a menu selection, or you can see the entire table of animals at JavaScript,JSON,MySQL: South Dakota Animals.

We'll start with a very simple PHP server that returns data in JSON format, for just one animal, when you tap a button. Next you can tap a button or select animals from a menu to see information returned from a MySQL database.

Learn two JSON techniques developers can use to send and retrieve data from a server. The first technique hard codes JSON values for return to the client. The second technique obtains JSON values from a MySQL table, to return to the client.

JSON Client-Server Examples

Tap a button or select a menu item, to see data from a server. These examples require an active PHP Web server to execute. You may copy the files to your Web server if necessary.

Tap: Requests Bison Information from a JSON Server from javascript21b-json-simple.php
Tap: Requests Pronghorn Information from MySQL and JSON.

The following menu retrieves values with JSON from MySQL.

JSON Client-Server Code

HTML Markup

Create two colored boxes and a drop down menu. Tap a box or select a menu item to activate a JavaScript function.

<div 
id="jGet" 
class="box aq"  
onclick="getSingle()">
Tap: Requests Bison Information from a JSON Server.
</div>

<div id="jSend" 
class="box peach" 
onclick="getAnimalInfo('Pronghorn')">
Tap: Requests Pronghorn Information from MySQL and JSON.
</div>

<h4>
Select an Animal from the Menu
</h4>

<select 
class="blk w100" 
id="json" 
onchange="getAnimal('json');">

<option 
value='Pronghorn'          
onclick="getAnimal('json');">
Pronghorn
</option>

<option 
value='Bison'              
onclick="getAnimal('json');">
Bison
</option>

<option 
value='Prairie Dog'        
onclick="getAnimal('json');">
Prairie Dog
</option>

<option 
value='Mountain Lion'      
onclick="getAnimal('json');">
Mountain Lion
</option>

</select>

<img 
id="ePicture" 
class="ex" 
src="../../thumbnails/ss-graphics-here.png" 
title="Graphics Display Here"
>

JavaScript

Send requests to a PHP server. Display results on the HTML Web page.

Obtain an image element and both box elements, for display of data.

See the JavaScript file json-to-from-server.js. I reduced comments for faster download time.

var ePicture = null;

/**
* Obtain the IMG to
* display all images.
*/
function getPictureElement(){
if(ePicture == null){
ePicture = document.getElementById('ePicture');
}
}

/**
* Just call a single response
* simple PHP server, javascript21b-json-simple.php.
* See javascript21b-json-simple.php below.
*/
function getSingle(){
getPictureElement();

// Create a download request.
const xmlhttp = new XMLHttpRequest();

// When the download completes:
xmlhttp.onload = function() {

// Convert server text to JSON:
const animalObj = JSON.parse(this.responseText);

// Obtain HTML element for
// information display:
let jGet = document.getElementById('jGet');

// Display the name, region and
// population for one animal:
jGet.innerHTML =  "The number of "+animalObj.name;
jGet.innerHTML += " near "+animalObj.region;
jGet.innerHTML += " is approximately "+animalObj.pop+".";

// Display the animal's photo.
ePicture.src = animalObj.image;
}

// Send the request to javascript21b-json-simple.php:
xmlhttp.open("GET", "https://code.7Thunders.biz/h5/js/javascript21b-json-simple.php");
xmlhttp.send();
}


/**
* Process send request for 
* information about one animal.
* Display received information.
* @param a: string name of animal.
*/
function getAnimalInfo(a){

// Obtain IMG element:
getPictureElement();

// Convert animal name
// to JSON format:
const dbParam = JSON.stringify(a);

// Prepare a download request:
const xmlhttp = new XMLHttpRequest();

// After download process
// the received data:
xmlhttp.onload = function() {

// Convert received data to JSON format:
const animalObj = JSON.parse(this.responseText);

// Obtain HTML element for text display:
let jSend = document.getElementById('jSend');

// Display the name, region and
// population for one animal:
let name = animalObj.name;
if(name == "Prairie Dog"){
jSend.innerHTML =  "The number of Prairie Dogs";
jSend.innerHTML += " living on "+animalObj.region;
}

else if (name == "Mountain Lion"){
jSend.innerHTML =  "The number of Mountain Lions";
jSend.innerHTML += " near "+animalObj.region;
}

else{
jSend.innerHTML =  "The number of "+animalObj.name;
jSend.innerHTML += " near "+animalObj.region;
}

let pop = animalObj.pop;
if (pop != 0){
jSend.innerHTML += " is approximately "+pop+".";
}
else{
jSend.innerHTML += " is unknown.";
}

// Display the image:
ePicture.src = "assets/"+animalObj.image;
}

// Send the request to
// javascript21c-json-sql.php
// Prepend URL with the animal name:
// javascript21c-json-sql.php?"+a
xmlhttp.open("GET", "https://code.7Thunders.biz/h5/js/javascript21c-json-sql.php?"+a);
xmlhttp.send();
}

/**
* Respond to JavaScript
* selection of one menu item.
* @param n: Menu ID.
*
* Obtain the value selected.
* Call getAnimalInfo(s)
* displayed above.
*/
function getAnimal(n) { 
var s = document.getElementById(n).value; 
getAnimalInfo(s); 
}

PHP

Peach Box & Menu > Animal Info & Photo

Tap the peach colored box or select a menu item. JavaScript sends a request, for the animal you select, to the PHP file named javascript21c-json-sql.php.

The peach colored box sends a request for Pronghorn only. The menu sends a request for the item you select from the drop down option list. Both the peach box and menu send the request to the same PHP file javascript21c-json-sql.php, displayed below.

The function getSQL() opens a connection to the database for MySQL table AnimalsSD. Most of the work's accomplished within the file functions.php, covered later on this page.

The following listing includes all of javascript21c-json-sql.php. PHP opens a set of functions in functions.php. PHP obtains the data sent, to the server, with getPutData(). PHP then opens the MySQL database named, AnimalsSD with function getSQL(). If a request for informtion about one animal was sent to the server, then data for one animal from the table's returned. Otherwise the entire table's returned.

<?php
include ('functions.php');
getPutData();
getSQL("AnimalsSD");
?>
Aqua Box > Bison Info with PHP

This first PHP file, named javascript21b-json-simple.php, simply JSON sends information, about American Bison, to the client. No SQL access is required. Tap the aqua box, above, to see the results.

Create an object with fields for name, population, region and a path to the image file. Convert the data to JSON format with json_encode(...). Echo displays the end result, which is also the data received by the client.

See the echoed information at javascript21b-json-simple.php. PHP file, javascript21b-json-simple.php includes the listing below.

<?php
$animalObj->name = "American Bison";
$animalObj->pop = 1500;
$animalObj->region = "Custer State Park, South Dakota";
$animalObj->image ="assets/bison.jpg";
$animalJSON = json_encode($animalObj);
echo $animalJSON;
?>
PHP to display HTML Table

The following PHP listing displays an HTML table from a MySQL table named AnimalsSD. See the full table at JavaScript,JSON,MySQL: South Dakota Animals.

Most of the work's accomplished within the file functions.php, covered below.

<?php
include ('functions.php');
showHeader("JavaScript,JSON,MySQL: South Dakota Animals","21A",20,"javascript21.php", "javascript22.php");
getPutData();
getSQL("AnimalsSD");
$s = '<h3 class="blk pt">Learn JavaScript with JSON</h3><p>Tap the left arrow button above, the <q>21</q> button below, or just return to <a href="javascript21.php" title="JavaScript: Client-Server with JSON, PHP & MySQL">JavaScript: Client-Server with JSON, PHP & MySQL</a> for more information about JavaScript with JSON.</p>';
showInfo($s);
showFooter();
?>
Functions PHP

File functions.php accomplishes one of two tasks, when executed.

File functions.php accesses a MySQL database to obtain information about one, or all, animals in the AnimalsSD table. If the URL's appended with an animal name, then just return JSON data for one animal. Otherwise display up to ten rows of the MySQL table, AnimalsSD. See the table at JavaScript,JSON,MySQL: South Dakota Animals.

The following listing includes all of functions.php.

<?php
// Data for connection
// to database:
include ('encrypted.php');

// Maximum number of rows
// to show in a table.
define("MAXROWS", 10);
$bShowTable = true;
$animalName = null;


/**
 * Render a Web page's header.
 * Readers probably want to modify
 * this code for their own Web site's header.
 
 * @param string $sTitle: Web page title.
 */
function showHeader($sTitle,$sPage, $n,$sLeft,$sRight){
 echo' <!DOCTYPE html>';
 echo' <html lang="en-US">';
 echo' <head><title>' . $sTitle . '</title>';
 echo' <meta name="description" content="' . $sTitle . '"/>';
 include('../../php/7-t-header-inside.php');
 echo '</head>';
 echo '<body  onload="loadDigit(' . $n . ')">';
 include ('../../php/7-t.php');
 echo '<main>';
 echo'<h1>'. $sTitle .'</h1>';
 echo'<h2 class="ctr"><button class="btn-next fl" onclick="window.location=\'' . $sLeft . '\'" title="JavaScript Features">◄</button>'. $sPage . '<button class="btn-next" onclick="window.location=\''. $sRight . '\'" title="JavaScript Features">►</button></h2>';
}


/**
* If the URL's appended with
* the name of an animal
* then assign $bShowTable = false
* because we don't want to show the table.
* Otherwise show the table.

* Also assign the value that was appended
* to the URL, to
* variable $animalName
* Later just information for
* $animalName is
* returned in JSON format.
*/
function getPutData(){
 global $animalName;
 global $bShowTable;
 
 $animalName = $_SERVER ['QUERY_STRING'];
 $animalName = urldecode($animalName);
 
 if ($animalName == null || strlen($animalName) == 0 || empty($animalName) || ctype_space($animalName)){
  echo '<h2>See All Animals in the Table</h2>';
  $bShowTable = true;
 } 
 else{
  $bShowTable = false;
 }
}

/**
 * Render a Web page's footer.
 * Readers probably want to modify
 * this code for their own Web site's footer.
 */
function showFooter(){
 include ('../../php/digits-js.php');
 echo'</main>';
 include ('../../php/7-f.php');
 echo '</body></html>';
}


/**
* Display the entire MySQL table
* to an HTML table.

* @param $result: Array of MySQL rows.
*/
function showTable($result){ 
 global $animalName, $bShowTable;
 if ($bShowTable == true){
  // Display the header:
  echo'<table><tr><th>Name</th><th>Region</th><th>Population</th><th>Image</th><th>Image Link</th></tr>';
 }
 
 // Display each row.
 if($result) {
  while($row = mysqli_fetch_array($result)){
    $name = $row['name'];
    $region= $row['region'];
    $img = $row['image'];
    $pop = $row['population'];
    $imglnk = $row['imglnk'];
    
    // A population of zero
    // indicates no one knows
    // the actual population.
    if ($pop == 0){
     $pop = "Unknown";
    }
    
    // Display each value in one row:
    echo '<tr><td>' . $name. '</td><td>' . $region.'</td><td>'. $pop . '</td><td>' . $img . '</td><td>' . $imglnk . '</tr>';
   }
  }
 echo'</table>';
}


/**
 * Obtain just the first row of
 * MySQL data.
 * Convert to an associative array.
 * Assign each cell to a property.
 * Convert the associative array to JSON format.
 */
function showJSON($result){
 if($result){
  //  Convert MySQL to an associative array:
  $row = mysqli_fetch_assoc($result);

  // Copy each cell as a string.
  $animalObj->name   = (string)$row['name'];
  $animalObj->region = (string)$row['region'];
  $animalObj->image  = (string)$row['image'];
  $animalObj->pop    = (string)$row['population'];
  
  // Convert the associative array to JSON format.
  $animalJSON = json_encode($animalObj);
  
  // Echo the JSON object.
  // JavaScript obtains this data,
  // for display in HTML.
  echo $animalJSON;
 }
}


/**
 * Execute a query or exit this program.
 * @param SQL Connection: $con
 * @param String $sQuery: string SQL Query.
 * @return: result of SQL query.
 
 * Null's never returned because this function
 * exits the program if the result's null.
 */
function getSQLQuery($con, $sQuery){

 // rows or an error value:
 $rValue = mysqli_query($con,$sQuery);
 
 if ($rValue == null){
  $sError = mysqli_error($con);
  echo ' error adding or updating: ' . $sError;
  
  // Exit the program
  // die(..) is an alias for exit(...)
  exit('Error: ' . $sError);
 }
 return $rValue;
}


/**
* Connect to the database.
* Select the database.
* Either display the entire table
* in HTML format or one row in JSON format.

* @param $tableName: String name of MySQL table.
*/
function getSQL($tableName){
 global $hostname,$username,$password,$dbname,$bShowTable,$animalName;
 $con = null;
 $sQuery = null;
 $sqlResult = null;
 
 // Connect to the database or exit:
 $con = mysqli_connect($hostname,$username, $password) OR DIE ('Unable to connect to database! Please try again later.');
 
 // Select our database:
 mysqli_select_db($con,$dbname);
 
 if($bShowTable == true){
  $sQuery = "SELECT * FROM " . $tableName;
  
  //Get all the rows from the table.
  $sqlResult =  getSQLQuery($con,$sQuery);  
  showTable($sqlResult);
 }
 
 else{
  $sQuery = "SELECT * FROM ". $tableName . " WHERE name = '{$animalName}'";

  $sqlResult = getSQLQuery($con,$sQuery);
  
  // Display one row
  // in JSON format.
  showJSON($sqlResult);
 }
 
 // Always close the
 // databse connection.
 mysqli_close($con);
}
?>

Summary

You learned to implement two JSON client-servers with JavaScript, PHP and MySQL. This page included explanation, source code and examples. The examples display information about animals in South Dakota, in response to one tap of a button, a menu selection, or you can see the entire table of animals at South Dakota Animals.

We started with a very simple PHP server that returns data in JSON format, for just one animal, when you tap a button. Next you can tap a button or select animals from a menu to see information returned from a MySQL database.

You learned two JSON techniques developers can use to send and retrieve data from a server. The first technique hard codes JSON values for return to the client. The second technique obtains JSON values from a MySQL table, to return to the client.

Learn JavaScript

JavaScript's the foundation of Web developer and Website design skills. This free and unique JavaScript tutorial includes some new or seldom used, but useful features.

Tags
canvas drawing, web design, web designing course, how to become a web developer, coding websites, website developers,learning web design, html web design, html5 canvas tutorials, coding Website, html5 canvas, learn to code, html5 canvas tutorial,learn html tutorial, simple html tutorial

Ads >
Create 3D Games: Learn WebGL Book 2 Simple Shaders: Learn WebGL Book 4
3D Programming for Beginners: Learn WebGL Book 1

for Web graphics!

Copyright © 2022 Amy Butler. All Rights Reserved.