Applet to JavaScript to PHP post to Database
The applet code was unchanged, but the JavaScript function was extended from:
<script type="text/javascript">
function updateWebPage(myArg)
{
document.getElementById("txt1").innerHTML=myArg;
}
</script>
to:
<script type="text/javascript">
function updateWebPage(myArg)
{
document.getElementById("txt1").innerHTML=myArg;
if (myArg=="")
{
document.getElementById("cbxItem").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("cbxItem").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","putitem.php?id="+myArg,true);
xmlhttp.send();
}
</script>
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>
</table>
The PH script was:
<?php
$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>";
mysql_close($con);
?>
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.
Comments
http://www.caspio.com/