Requirements:
Basic HTML and Javascript Knowledge. You should also need at least some "hello world" experience in a server-side language like php or java.
<script type="text/javascript" src="prototype/prototype.js"></script>
<input type="text" name="multiplier" id="multiplier" size="2" maxlength="2" /> * <input type="text" name="multiplicand" id="multiplicand" size="2" maxlength="2" />
<input type="button" name="button" id="button" onclick="test()" value="Submit" /> <div id="testdiv" style="border:1px #000000 solid; padding:10px; font-size:20px; height:50px;"></div>
<?php $data = array(); $data['validation'] = false; /*
Just a simple validation. If we receive a non-numeric value, then let us return the array with
validation value set to false, which is the default. the json_encode function will convert the
php array into json notation, which in fact is plain text: */
if(!is_numeric($_POST['multiplier']) || !is_numeric($_POST['multiplicand'])){ print json_encode($data); return; } # Yes! we have received numeric values, now we can safely make the mathematical operation: $data['validation']=true; $data['result'] = $_POST['multiplier'] * $_POST['multiplicand']; print json_encode($data); ?>
<script type="text/javascript">
function test() { /* Instatiate the Ajax object. let me explain its parts:
'data.php'
the target page which we want to get data from, or just make a request, like the
action attribute in html forms. method:'post' the request method, just like html forms.
parameters The data that we want to send. onsuccess this function is executed when the Ajax object makes the remote call without problems.
the 'transport' argument is an object that contains detailed info. about the response.
Also contains the data returned from the taget page, which resides in the responseText property. */ new Ajax.Request('test.php', { method:'post', parameters: { /* Get the values from html input fields and send the data as POST */
multiplier:document.getElementById('multiplier').value, multiplicand:document.getElementById('multiplicand').value }, onSuccess: function(transport){ var response = transport.responseText.evalJSON();
el = document.getElementById('testdiv'); el.innerHTML="The result from php is: "+response.result; }, onFailure: function(){ alert('Something went wrong...'); } } ); }
If you need futher help, you can contact me at: comments at ajaxcode dot net