www.webdeveloper.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 25

Thread: Assigning a js variable to a php variable

  1. #1
    Join Date
    Dec 2012
    Posts
    8

    Assigning a js variable to a php variable

    Hi,
    I need to assign a JS variable to a PHP variable. Even though I can do it in a simple program, I can’t make it work in a slightly imbricated one.

    In this program, I am in a JS loop, where I call a « google map API ». In this loop, for each flag displayed on the map I will attach a marker. The contents of the marker is coming from a PHP function (meteorlogical information). Cannot do otherwise beacause I am using « file_get_contents » and it is very difficult to do that in JS (HttpRequest for example won’t work for this specific URL).

    The contents returned by the PHP function is therefore indexed to the JS loop index. Since these are parallel, I also used a "$i=0;" then "$i++;" but this will execute only once. I get "$i=1", but then it stays at this value. So I get the same marker on every flag !!

    Basically I need « $i=j » or « $i++ » to work. As I said, the following simple code works fine :

    Var j=’Hello’;
    <? $i='<script>document.write(j);</script>';
    Echo $i ?> will produce ‘Hello’.

    Thanks and happy holidays.

  2. #2
    Join Date
    Aug 2008
    Location
    Sweden
    Posts
    227
    Sounds like you're trying to do something very weird. Are you not making a http/Ajax request with JavaScript? Or are you doing this at page load?

    In either case, use the $_GET or $_POST associative arrays to access data send from the client to the server.
    New to web development or in need of a good reference? Check out the Mozilla Developer Network or W3Schools.

  3. #3
    Join Date
    Dec 2012
    Posts
    8
    May look so, but ..

    Here's the initial scenario: From the server side I read a file containing information on the 100 meteorological stations (geographical coordinates). This is PHP.

    Then to JS. Easily the information is put into JS variables and with var map= new google.maps.Map .... I display 100 flags on the map with the names of the stations. So this is page load. A very nice map, and you can even get the phone number of the station by putting your mouse on it. Everything is good.

    So now the 2nd part. For all of these stations I get meteorological information which I display with "var marker=new google.Maps.marker. And if the user clicks on the flag he gets the information. So as I said works for the first one.

    These two mecanisms I've already made work separately. You can see them in my blog. Here you have the map "http://www.volets10.fr/V10stationsmeteo.php" and here you have the meteo (for Roissy CDG) "http://www.volets10.fr/V10metarETtafV5.php"

    If I could go to this site "http://aviationweather.gov/adds/meta...ation_ids=LFPG" and get the results with JS (httprequest) everything would be ok. But it doesn't work for these URL. Therefore I use file_get_contents which of course works.

    Not so weird, but ... I am desperately looking for a solution. There shouldn't be any page re-loads.
    Cheers.

  4. #4
    Join Date
    Nov 2010
    Posts
    1,087
    I'm not 100% sure on what you are trying to do, but it seems that this request is closer to what you should be making:
    http://aviationweather.gov/adds/data...ursBeforeNow=1

    it would be nice if you could get it in JSON, but parsing the xml is no big deal.
    Last edited by xelawho; 12-30-2012 at 08:05 AM.

  5. #5
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,268
    Use simply an Ajax call (for each click on a station) with something like this
    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta name="generator" content="PSPad editor, www.pspad.com">
    <title></title>
    <style type="text/css">
    
    </style>
    </head>
    <body>
    <div id="rsp"></div>
    <script type="text/javascript">
    (function(){
    	var xmlObj=false;
    	var xmlFct=[function(){return new XMLHttpRequest()}
    		,function(){return new ActiveXObject("Msxml2.XMLHTTP")}
    		,function(){return new ActiveXObject("Msxml3.XMLHTTP")}
    		,function (){return new ActiveXObject("Microsoft.XMLHTTP")}];
    	for (var i=0;i<xmlFct.length;i++) {try{xmlObj = xmlFct[i]();}catch(e){continue;}break;}
    	
    	return sndRqt=function(url,cllbck,pstDta){
    		var req=xmlObj;
    		if (!req) return;
    		var mth=(pstDta)? "POST":"GET";
    		req.open(mth,url,true);
    		req.setRequestHeader('User-Agent','XMLHTTP/1.0');
    		if (pstDta) req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
    		req.onreadystatechange=function(){
    			if (req.readyState!=4) return;
    			if (req.status!=200 && req.status!=304) return;
    			cllbck(req);}
    		if (req.readyState==4) return;
    		req.send(pstDta);
    	};
    }());
    var stt='LFPG'; 
    sndRqt('ajx_mtr.php?arp='+stt,function(r){alert(r.responseText)});
    
    </script>
    </body>
    </html>
    And a php file ajx_mtr.php
    Code:
    <?php
      header("Content-Type: text/html; charset=utf-8");
      if (!empty($_GET["arp"])){$arp=$_GET["arp"];
    	$mtr=file_get_contents("ftp://tgftp.nws.noaa.gov/data/observations/metar/decoded/".$arp.".TXT");
      	exit($mtr);}
      exit("No response !");
    ?>

  6. #6
    Join Date
    Dec 2012
    Posts
    8
    OK thanks, let me work on that. In the meanwhile I did get the result which I wanted (for 10 stations not 100) by typing out "manually" one by one the call to the php function !! Naturally, the sequence of the station list MUST NOT CHANGE. Or, people will not understand the weather over their heads :-)

    Here it is : http://www.volets10.fr/V10stationsmeteo_NX.php.

    V10stations_liste.txtV10stationsmeteo_NX.txt

  7. #7
    Join Date
    Dec 2012
    Posts
    8
    Thank your for your answer. But my problem is not parsing, it's getting what to parse :-) Please see my reply to 007Julien below.

  8. #8
    Join Date
    Dec 2012
    Posts
    8
    Yes and yes. I have your script up and running. And indexed in JS !!!!!
    All I have to do now is to adapt it to my scenario. I'll post the outcome quickly.
    Thank you so much.

  9. #9
    Join Date
    Dec 2012
    Posts
    8
    I was so excited .. I di not see that you changed the URL. This is an ftp server nws.noaa which has a bad habit of sending you one of many txt files which MAY NOT BE the latest for that station. You have to upload all and pick up the latest. This is true for METAR and TAF.
    In fact the best (international) results can be ontained from the following :
    http://meteocentre.com/cgi-bin/get_metar_taf?STN=LFPG (METAR and TAF)
    http://aviationweather.gov/adds/meta...bmitmet=Submit (METAR)
    http://aviationweather.gov/adds/meta...ation_ids=LFPG (TAF)
    For the lat two the results obtained come formatted(XML, HTML).
    I will look into this soon.
    Thanks again.

  10. #10
    Join Date
    Dec 2012
    Posts
    8
    Hi,
    Kindly make this work for two stations one after the other..like :
    var stt='LFPG';
    sndRqt('V10ajx_mtr.php?arp='+stt,function(r){
    alert(r.responseText)
    });

    var stt='LFOP';
    sndRqt('V10ajx_mtr.php?arp='+stt,function(r){
    alert(r.responseText)
    });
    I think we have a synhcronisation problem. The Httprequest must be synchronuous I think? Otherwise I get the second content and not the first one !!

  11. #11
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,268
    You have not to call this function at the opening of the page, but only with the user's click !
    Last edited by 007Julien; 12-30-2012 at 12:36 PM.

  12. #12
    Join Date
    Nov 2010
    Posts
    1,087
    but is it really so necessary to get up to the second information that you make an ajax call with every click on a marker? how long do you think people will be looking at your page for that the information will become outdated between the time they click on the markers?

    Looking back on your original post, I think you were having a problem with function closure. You can have a look at one solution, below, calling createMarker function from within the loop (and using the yql to get the data, because I don't know php ):

    Code:
    <!DOCTYPE html>
    <html>
    <head>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
    <style>
    html, body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
    
    #map_canvas {
      height: 100%;
    }
    </style>
    </head>
    <body>
    <div id="map_canvas"></div>
    <script type = "text/javascript">
    var infowindow = new google.maps.InfoWindow();
    var stations=[];
    function getData (data) {
      stations=data.query.results.response.data.METAR;
      var scr=document.createElement("script");
      scr.src="http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%20%3D%22http%3A%2F%2Faviationweather.gov%2Fadds%2Fdataserver_current%2Fhttpparam%3FdataSource%3Dstations%26requestType%3Dretrieve%26format%3Dxml%26stationString%3DLFPG%2520LF*%22&format=json&callback=makeMap"
      document.body.appendChild(scr);
      }
      
    function makeMap(deets){ 
    var details=deets.query.results.response.data.Station;
      var mapOptions = {
              zoom: 7,
              center: new google.maps.LatLng(46.76305556,2.424722222),
              mapTypeId: google.maps.MapTypeId.ROADMAP
            };
    
            var map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions);
            for (var i = 0; i < stations.length; i++) {
            var point= new google.maps.LatLng(stations[i].latitude, stations[i].longitude);
    		var label= stations[i].station_id;
    		for (var a = 0; a < details.length; a++) {
    		if(details[a].station_id==label){
    		var name=details[a].site;
    		break;
    				}
    		}
    		var temp=stations[i].temp_c;
    		var dir=stations[i].wind_dir_degrees;
    		var sp=stations[i].wind_speed_kt;
    		var vis=stations[i].visibility_statute_mi;
    		var str=name+"<br>temperature: "+temp+"<br>"+"wind direction: "+dir+"<br>"+"wind speed: "+sp+"<br>"+"visibility: "+vis;
            var marker = createMarker(point,label,str,map);
    		  }
      }
    
    		function createMarker(latlng, label, html,map) {
    		var marker = new google.maps.Marker({
            position: latlng,
    		title:label,
            map: map,
            zIndex: Math.round(latlng.lat()*-100000)<<5
            });
    
    		google.maps.event.addListener(marker, 'click', function() {
            infowindow.setContent(html); 
            infowindow.open(map,marker);
            });
        }
    
    </script>
    <script type="text/javascript" src="http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%20%3D%20%22http%3A%2F%2Faviationweather.gov%2Fadds%2Fdataserver_current%2Fhttpparam%3FdataSource%3Dmetars%26requestType%3Dretrieve%26format%3Dxml%26stationString%3DLFPG%2520LF*%26hoursBeforeNow%3D1%22&format=json&diagnostics=true&callback=getData"></script>
    </body>
    </html>

  13. #13
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,268
    It remains only to modify the contents of InfoWindow and attach it to the marker before opening :
    Code:
    <script> 
    (function(){
    	var xmlObj=false;
    	var xmlFct=[function(){return new XMLHttpRequest()}
    		,function(){return new ActiveXObject("Msxml2.XMLHTTP")}
    		,function(){return new ActiveXObject("Msxml3.XMLHTTP")}
    		,function (){return new ActiveXObject("Microsoft.XMLHTTP")}];
    	for (var i=0;i<xmlFct.length;i++) {try{xmlObj = xmlFct[i]();}catch(e){continue;}break;}
    	return sndRqt=function(url,cllbck,pstDta){
    		var req=xmlObj;
    		if (!req) return;
    		var mth=(pstDta)? "POST":"GET";
    		req.open(mth,url,true);
    		req.setRequestHeader('User-Agent','XMLHTTP/1.0');
    		if (pstDta) req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
    		req.onreadystatechange=function(){
    			if (req.readyState!=4) return;
    			if (req.status!=200 && req.status!=304) return;
    			cllbck(req);}
    		if (req.readyState==4) return;
    		req.send(pstDta);
    	};
    }());
    var stations = [[]];
    stations[1]=['LFAQ','ALBERT','',' ',49.9725,2.69138888888889];
    stations[2]=['LFAT','LE TOUQUET','123.125','03 21 06 62 84',50.5147222222222,1.6275];
    stations[3]=['LFBA','AGEN','129.6',' ',44.1747222222222,0.590555555555556];
    stations[4]=['LFBC','CAZAUX','',' ',44.535,-1.13138888888889];
    stations[5]=['LFBD','BORDEAUX MERIGNAC','131.150','05 57 92 81 04',44.8286111111111,-0.715277777777778];
    stations[6]=['LFBE','BERGERAC','127.475','05 53 63 53 55',44.8244444444444,0.520555555555556];
    stations[7]=['LFBG','COGNAC','244.450',' ',45.6583333333333,-0.3175];
    stations[8]=['LFBH','LA ROCHELLE','126.875','05 46 00 13 92',46.1791666666667,-1.19527777777778];
    stations[9]=['LFBI','POITIERS','121.775',' ',46.5875,0.306666666666667];
    stations[10]=['LFBL','LIMOGES','128.075','05 55 48 40 37',45.8608333333333,1.18027777777778];
    	var centre = new google.maps.LatLng(47.76305556	,2.424722222); 
    	var mapOptions = {
    		zoom: 7, // presque toute la France
    		center: centre, //centre 
    		mapTypeId: google.maps.MapTypeId.ROADMAP // type road (sinon SATELLITE OU HYBRID ou TERRAIN
    	}
    	var map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions); // et afficher utilisant le conteneur map_canvas
    	var image = new google.maps.MarkerImage('http://www.volets10.fr/V10div/beachflag.png',
    			new google.maps.Size(20, 32),			
    			new google.maps.Point(0,0),			
    			new google.maps.Point(0, 32));
    	var shadow = new google.maps.MarkerImage('http://www.volets10.fr/V10div/beachflag_shadow.png',			
    			new google.maps.Size(37, 32),
    			new google.maps.Point(0,0),
    			new google.maps.Point(0, 32));
    	var shape = {
    			coord: [1, 1, 1, 20, 18, 20, 18 , 1],
    			type: 'poly'};
    	for ( i = 1; i < stations.length; i++) // on va dérouler les stations
    	{
    		var station = stations [i];
    		var myLatLng = new google.maps.LatLng(station[4], station[5]);
    		titre=station[0]+"/"+station[1]+"\n"+station[2]+"/"+station[3]
    		var marker = new google.maps.Marker({  // ça va afficher un flag avec son ombre sur les stations et le nom, la fréquence et le no de tél avec onmouseover
    				position: myLatLng,
    				map: map,
    				shadow: shadow,
    				icon: image,
    				shape: shape,
    				title: titre // nom de la stations
    		});
    google.maps.event.addListener(marker,'click',function(){
    	var msg;alert(this.title.substr(0,4))
    	sndRqt('ajx_mtr.php?arp='+this.title.substr(0,4),function(r){msg=r.responseText;alert(msg);
    		
    		// To remain ! It's don't work ??? 
    		var infWindow = new google.maps.InfoWindow({content:msg}); 
    		infWindow.open(map,this);});});
    }
    </script>
    </div>
    </body>
    </html>
    Peut-être convient-il de définir (au préalable) une seule InfoWindow à déplacer sur le marqueur (accessible par this) avant ouverture...À mon avis ce n'est plus qu'un problème avec Google maps.
    Last edited by 007Julien; 12-30-2012 at 06:57 PM. Reason: correction red color

  14. #14
    Join Date
    Nov 2010
    Posts
    1,087
    Quote Originally Posted by 007Julien View Post
    Peut-être convient-il de définir (au préalable) une seule InfoWindow à déplacer sur le marqueur (accessible par this) avant ouverture...À mon avis ce n'est plus qu'un problème avec Google maps.
    that's what this piece of code does...
    Code:
    var infowindow = new google.maps.InfoWindow();
    ...
    
    		google.maps.event.addListener(marker, 'click', function() {
            infowindow.setContent(html); 
            infowindow.open(map,marker);
            });
    makes one globally accessible infowindow and places a listener on each marker so that the one window will move and change contents on the click. If you make the markers in the loop like you are doing you don't get closure.

  15. #15
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,268
    Yes. We have also to call the request before too define the html ! For me it does not work ???

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles