Page 1 of 1

Always take the weather with you, a php ajax how-to.. using ajax to display data from the server, a php javascript, combo.. Rate Topic: -----

#1 kiwi2  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 8
  • View blog
  • Posts: 178
  • Joined: 16-September 08

Posted 20 January 2009 - 04:42 AM

The most riveting discovery, for me at least, has been ajax(AJAX stands for Asynchronous Javascript And XML.(for a brilliant article on the subject, see:-The Programming Underground. tomodule=blog&blogid=1148showentry=1219, under blogs on this site)), this protocol, made famous by Google Search's spell suggest program, has long had a bad name amonst coders and internet surfers alike, the reason being, those nasty Loading... messages we have all seen in and around the net, that do nothing other than, well display the message Loading...
Ajax is, however, the most useful tool you are currently likely to find, its greatest benefit being that, without having to reload a page, data can be displayed in fairly large bytes, in a manner which is not only conservative in space, but is impressive on the eye.
Ajax is not really a language in itself but a clever combination of Javascript, PHP, or ASP(which ever server side language you prefer) and in advanced coding XML, it allows Javascript, the powerful browser language, developed by Nescape, to suddenly have serverside capability, thus making the language doubly engmatic.
Well, now how does it work... The term Ajax was coined by Jesse James Garret, in 2005 when he used it as an acronym for the tools he was preposing to a client for further reading see


http://www.adaptivep...ives/000385.php


Ajax uses the XMLHttpRequest object to retrieve data from the server, sending back a series of state changes each with their own code for easy access(onreadystatechange propery).


The stages are as follows, 0-request begun,1-request set up,2,request sent,3-request in process,4-request complete.
The single most important aspect to consider if you want ajax to work properly, thereby preventing the Loading and little else message, is to see that the code will work in a variety of browsers, testing the code with suitable methods for each browser with a built in try.. catch exception works well.

function getob()
{
var request=null;

try
 {
 // Firefox, Opera 8.0+, Safari
 request=new XMLHttpRequest();
 }
catch (e)
 {
 // Internet Explorer
 try
  {
  request=new ActiveXObject("Msxml2.XMLHTTP");
  }
 catch (e)
  {
  request=new ActiveXObject("Microsoft.XMLHTTP");
  }
 }
return request;
}  


This code, which by the way, seems to be exactly how everyone writes it, tests each browser, sending an error alert to an outdated browser, this code even works on updated javascript enabled mobile phones.
Now lets get to our application, everybody it seems wants a weather forecast on their pages, and with a little help from phpweather, and ajax, a smart little weather app is only minutes away.
download phpweather from gimpster.com, or sourceforge.net, load it to your server, this software contains, the sexiest array I have ever seen which in the words of the coder concerned- quote..
PHP Weather is a script that makes it easy to show the current weather on your webpage. Airports all over the world make a so-called METAR report once an hour. A METAR report is an aviation weather report to be used primarily by airplanes. The report contains data, in a shorthand form, about temperature, wind speed and direction, cloud-coverage and much more. PHP Weather converts this format into both imperial and metric units, and makes them easily available-..
end quote.
go to -
http://www.nws.noaa....oso/site.shtml-
to get the weather station identifiers for the country you wish to display data for(also contained in the station.csv file of phpweather).
(phpweather is a fully self contained package, all the necessary documentation and how to use it are included, however this tutorial is not a description for phpweather but rather uses the package to demonstrate the workings of ajax.)
Once your package is unzipped to your server, open the dir phpweather-2.2.2, make a new file call it station.html, and copy the following code into it which gives the weather forecasts for cities
in South Africa
<style>
#fh{background-color: tan;
color: brown;
font-family: Impact;
width: 50%;
margin: 50px;
padding: 10px;
border: 2px solid brown; }
</style>
<script>
var request="null";

function aj(wo)
{ 
request=getob()
if (request==null)
 {
 alert ("Browser does not support ajax")
 return
 } 

request.onreadystatechange=state;
request.open("GET", "http://www.somesite.co.za/phpweather-2.2.2/test3.php?q="+wo, true); 
		request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
		request.send(null); 


}

function state() 
{ 
 if (request.readyState==4 || request.readyState=="complete")
 { 
 document.getElementById("forecast").innerHTML=request.responseText 
 } 
else 
{ 

 document.getElementById("forecast").innerHTML= "Loading forecast, please wait...."; 
} 
}

function getob()
{
var request=null;

try
 {
 // Firefox, Opera 8.0+, Safari
 request=new XMLHttpRequest();
 }
catch (e)
 {
 // Internet Explorer
 try
  {
  request=new ActiveXObject("Msxml2.XMLHTTP");
  }
 catch (e)
  {
  request=new ActiveXObject("Microsoft.XMLHTTP");
  }
 }
return request;
} </script>

<div id='fh'>Select location:<br /><form name='asta'><select id='stations' onchange="aj(this.value);">
<option>Select...</option>
<option value='FAAB'>Alexander Bay</option>
<option value='FABL'>Bloemfontein, Bloemfontein Airport</option>
<option value='FACT'> Cape Town, Cape Town International Airport</option>
<option value='FADN'>
Durban, Durban International Airport</option>
<option value='FAEL'>
East London, East London Airport</option>
<option value='FAEO'>
Ermelo</option>
<option value='FAFF'>
George, George Airport</option>
<option value='FAHS'>Hoedspruit</option>
<option value='FAJS'>
Johannesburg International Airport</option>
<option value='FAKM'>
Kimberley, Kim-Apt</option>
<option value='FAKD'>
Klerksdorp</option>
<option value='FALA'>Lanseria</option>
<option value='FALT'>
Lichtenburg</option>
<option value='FAMM'>
Mafikeng Intl. Ad</option>
Mossel Bay Cape Saint Blaize</option>
<option value='FANS'>Nelspruit</option>
<option value='FANC'>Newcastle</option>
<option value='FAPE'>Port Elizabeth, Port E Apt</option>
<option value='FAPS'>
Potchefstroom</option>
<option value='FAGM'>
Rand</option>
<option value='FARG'>Rustenburg</option>
Springbok</option>
<option value='FASI'>
Springs</option>
<option value='FASR'>Standerton</option>
<option value='FAUT'>
Umtata</option>
<option value='FAUP'>
Upington, Up-Apt</option>
<option value='FAVV'>Vereeniging</option>
<option value='FAWI'>Witbank</option>
<option value='FAWB'>Wonderboom / Pretoria</option></select></form>Forecast<div id='forecast'></div></div> 
 



You don't have to be a genius to work out that you must change the weather station data to that of your own choosing.
You could set up a txt file with the values delimited with commas or |'s then use php's file() function to construct an associative array for the forms values ie:

echo "<select>";

foreach ($station as $key => $val) 
{ 
echo '<option value="$key">' . $val . '</option>';
} 
echo "</select>";
?> 


or you can hard code them in as I have done, it comes to about the same amount of work, but the latter method is infinitly more elegant.
Now to the code.
first we set up an empty variable to handle the new XMLHttpRequest
ie var request.
then we build a get url of values to send to the server using the open() function, we wait on the server while displaying a loading message, and then finally the data is displayed using the document.getElementById().innerHTML method.
The attendant php file test3.php codes as follows-
<?php
error_reporting(E_ALL);
require('phpweather.php');
$q = $_GET['q'];
$url ="http://weather.noaa.gov/pub/data/observations/metar/stations/" . $q . ".TXT";
$req = file_get_contents($url);
$metar = $req;
$language = 'en';
$weather = new phpweather();
?>
<?php
if (!empty($metar)) {
$weather->set_metar($metar);
 require(PHPWEATHER_BASE_DIR . "/output/pw_text_$language.php");
require(PHPWEATHER_BASE_DIR . "/output/pw_images.php");
  
$type = 'pw_text_' . $language;
$text = new $type($weather);
echo "<p>\n" . $text->print_pretty() . "</p>\n";
$icons = new pw_images($weather);
echo '<p><img src="'.$icons->get_sky_image().'" /> ';
echo '<img src="'.$icons->get_winddir_image().'" /> ';
echo '<img src="'.$icons->get_temp_image().'" /></p>';

  

}

?> 


the php file handles the requset in the normal fashion, and echo's out the data which is then displayed by station.html.
and that's all there is to it.
further reading and resources.
http://ajaxian.com/a...p-mvc-framework

http://jquery.com/

Query is a fast and concise Javascript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write Javascript.

http://www.prototypejs.org/


Featuring a unique, easy-to-use toolkit for class-driven development and the nicest Ajax library around, Prototype is quickly becoming the codebase of choice for web application developers everywhere.
w3schools ajax tutorial.

This post has been edited by kiwi2: 26 January 2009 - 10:43 PM


Is This A Good Question/Topic? 1
  • +

Page 1 of 1