This time, I want to share about XMLHttpConnection. I learn this thing because I need it to develop my (first) BlackBerry application. What is the purpose of XMLHttpConnection? With XMLHttpConnection, I can request a connection in background without reloading the page (something like that). Nah, I tried it and it was successful. Now, it's time to share. I'll show you step by step.
note: this XMLHttpConnection example using GET method. For POST method, I'll post it later.
First, let's create a simple HTML file. This is my HTML file with some JavaScript code:
<script type="text/javascript"> function getIt(xx){ var get= parent.document.getElementById(xx); if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.open("GET","http://localhost/xmlcon/connect.php?field1="+get.innerHTML,false); xmlhttp.send(); alert(xmlhttp.responseText); xmlhttp.close(); } </script> <html> Simple XML HTTP Request <body style="font-size: 3em"> <div id="test2" onClick="getIt('test2')">2</div> <div id="test1" onClick="getIt('test1')">1</div> </body> </html>Save as main.html and test it in my localhost and the result is like this:
Next step, create a dummy data in your database. I create a dummy table inside my database. I create XML database and dummydata table. Last, create a PHP file to handle the request. Here is my PHP code, saved as connect.php:
<?php $username="root"; $password=""; $database="xml"; $field1=$_GET['field1']; $con= mysql_connect("localhost","<your username>","<your password>"); mysql_select_db($database) or die("unable to select the database.."); if($con) { echo "Result: \n"; $query="select * from dummydata where id='$field1'"; $res=mysql_query($query); $done=mysql_fetch_array($res); if($done['content']!=null) { echo $done['content']; } else { echo "NULL"; } } else { echo "Invalid login information!"; } mysql_close($con); ?>
Don't forget to change the username and password for your database. It's time to test it in the browser. Run main.html in your browser and click number 1 or number 2 there. Clicking number 1 = iPod and clicking number 2 = Computer (like what you wrote in your table).
Simple, right? Now it's your turn. If you don't understand about the code above, leave a comment here and I'll try to explain it to you :) Thanks!
No comments:
Post a Comment