Tuesday, September 20, 2011

Applet to JavaScript to PHP post to Database

This post brings together the previous two. In the first, I called PHP code from a JavaScript function using an AJAX command. In the second, I passed an SQL command to a JavaScript function. In this post I describe bringing the two together. Instead of simply displaying the SQL in a text box on the web page, passing it to a PHP file.

The applet code was unchanged, but the JavaScript function was extended from:

<script type="text/javascript">
function updateWebPage(myArg)


<script type="text/javascript">
function updateWebPage(myArg)
if (myArg=="")
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
if (xmlhttp.readyState==4 && xmlhttp.status==200)

And the HTML table had an extra couple of cells added:

<table border=1 align='center' cellpadding=0 cellspacing=0 >
<tr><td style='text-align:center; background-color:#C0C0C0'>Compiled Java Applet</td></tr>
<tr><td><applet code="JSHelloWorld2.class"
width="500" height="80" MAYSCRIPT style="border-width:0;" name="jsap" id="jsap">
</applet> </td></tr>
<tr><td style='text-align:center; background-color:#C0C0C0'>HTML Textbox filled by JavaScript</td></tr>
<tr><td><textarea style='width:500px; height:50px' name='txt1' id='txt1'>Query goes here</textarea></td></tr>
<tr><td style='text-align:center; background-color:#C0C0C0'>HTML diagnostic messages rendered by PHP script</td></tr>
<tr><td><div id="cbxItem">PHP info will populate this space</div></td></tr>

The PH script was:

$id = $_GET['id'];
include('dbinfo.php');// collect database variables and connect.
$con = mysql_connect( $dbhost, $dbuser, $dbpass );
if (!$con)
die('Could not connect: ' . mysql_error());
mysql_select_db($dbname, $con);
// first use encodeURIComponent on javascript to encode the string
// receive json string and prepare it to json_decode
$jsonStr = stripslashes ($id);
$query = $jsonStr;
$result = mysql_query($query) or die(mysql_error());
echo"<p>The query is: $query </p>";
echo"<p>The result is: $result </p>";


I hate it when people put obscure references in code, so for anyone who has not been following this blog, the dbinfo.php structure was given in the Simple Web Application – Data Display page.

On opening, the web page looked as shown below:

And after clicking the button on the applet, it was as shown below:

The result of 1 (or true) returned by the query indicated that a line had been successfully inserted. Inspection of the database using the Simple Web App, confirmed that this was the case. The only minor problem was the loss of the plus sign in "Itemdet", but that can be fixed.

1 comment:

lawtonterri said...

Fantastic post. Here’s a tool that lets your build your online database without programming. There is no need to hand code PHP. Cut your development time by 90%