News:

If you would like to join this forum send an e-mail to support@scriptbasic.org.

Main Menu

ScriptBasic using AJAX

Started by John Spikowski, Nov 12, 2022, 04:39 PM

Previous topic - Next topic

John Spikowski

This EXAMPLE shows how AJAX can be used with the ScriptBasic application http proxy server. A drop down list control is used to select the product line you wish to be shown and does an AJAX call to populated the grid.

sbajax
' ScriptBasic AJAX & MySQL

IMPORT cgi.bas

cgi::Header 200,"text/html"
cgi::FinishHeader

PRINT """
<html>
<head>
<script>
function showItems(str) {
  if (str == "") {
    document.getElementById("results").innerHTML = "";
    return;
  } else {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        document.getElementById("results").innerHTML = this.responseText;
      }
    };
    xmlhttp.open("GET","/home/qbo/getitems.sb?q="+str,true);
    xmlhttp.send();
  }
}
</script>
</head>
<body>

<form>
  <select name="items" onchange="showItems(this.value)">
    <option value="">Product Line</option>
    <option value="Classic Cars">Classic Cars</option>
    <option value="Motorcycles">Motorcycles</option>
    <option value="Planes">Planes</option>
    <option value="Ships">Ships</option>
    <option value="Trains">Trains</option>
    <option value="Trucks and Buses">Trucks and Buses</option> 
    <option value="Vintage Cars">Vintage Cars</option>
  </select>
</form>
<br>
<div id="results"></div>

</body>
</html>
"""

getitems.sb
' AJAX - getitems.sb

IMPORT cgi.bas
IMPORT mysql.bas

cgi::Header 200,"text/html"

PRINT """
<!DOCTYPE html>
<html>
<head>
<style>
table {
  width: 100%;
  border-collapse: collapse;
}

table, td, th {
  border: 1px solid black;
  padding: 5px;
}

th {text-align: left;}
</style>
</head>
<body>
"""

product_line = cgi::GetParam("q")

dbh = mysql::RealConnect("localhost","USER","PASSWORD","classicmodels")
mysql::query(dbh,"SELECT * FROM products WHERE productLine = '" & product_line & "'")

PRINT """
<table>
  <tr>
    <th>Product Code</th>
    <th>Product Line</th>
    <th>Product Vendor</th>
    <th>Product Name</th>
    <th>In Stock</th>
    <th>Cost</th>
    <th>MSRP</th>
  </tr>
"""

WHILE mysql::FetchHash(dbh,column)
  PRINT "  <tr>\n"
  PRINT "    <td>", column{"productCode"}, "</td>\n"
  PRINT "    <td>", column{"productLine"}, "</td>\n"
  PRINT "    <td>", column{"productVendor"}, "</td>\n"
  PRINT "    <td>", column{"productName"}, "</td>\n"
  PRINT "    <td align=\"right\">", column{"quantityInStock"}, "</td>\n"
  PRINT "    <td align=\"right\">", FORMAT("%~$###.00~",column{"buyPrice"}), "</td>\n"
  PRINT "    <td align=\"right\">", FORMAT("%~$###.00~",column{"MSRP"}), "</td>\n"
  PRINT "  </tr>\n"
WEND

PRINT """
</table>
</body>
</html>
"""

mysql::Close(dbh)