1

This is my first post here so thanks in advance for your help.

I have a piece of PHP code for getting an airport METAR and displaying it. The code 'metar.php' is as follows:

<?php

$location = "EGLL";

get_metar($location);

function get_metar($location) {
$fileName = "http://weather.noaa.gov/pub/data/observations/metar/stations/$location.TXT";
    $metar = '';
    $fileData = @file($fileName) or die('METAR not available');
    if ($fileData != false) {
            list($i, $date) = each($fileData); 

            $utc = strtotime(trim($date));
            $time = date("D, F jS Y g:i A",$utc);

            while (list($i, $line) = each($fileData)) {
                    $metar .= ' ' . trim($line);
                    }
            $metar = trim(str_replace('  ', ' ', $metar));
            }

    echo "<div style=\"color: white;\">METAR FOR $location (Issued: $time UTC):<br>$metar</div>";
    }
 ?>

Currently, there are buttons on the frontpage of my website that redirect to website.com/metar.php when the button is clicked. The code is as follows:

 <li><button type="submit" style="height: 40px;" class="btn btn-primary" onclick="window.location.href = '/heathrow.php'"/>METAR At London Heathrow</button></li>

I would appreciate it if someone can tell me how to change this code so that the button is replaced by the output of metar.php when it is clicked rather than having to redirect to website.com/metar.php when the button is clicked.

I hope that made sense
Thank you very much again in advance!

7
  • Welcome to SO ! Please read the How to ask page. You'll notice you're supposed to show us what you've tried which is not the case for the moment. As it is sometimes hard to even know where to start, here are some tips : you will need to use javascript to do that. More specificically, to request the page you will need to use AJAX. That said, you seem to also have the hands on that metar.php page, so you might just aswell get this data server-side on your frontpage, place it somewhere in your HTML but hide it, and show it upon button click. Commented Jan 9, 2015 at 8:16
  • Sorry. As I said it is my first question on the site. Would you mind posting an answer to show how I might be able to hide it and show it when the button is clicked? Thanks again. Commented Jan 9, 2015 at 8:17
  • 1
    You can perform an AJAX request in order to accomplish such. In any case, since PHP is a server-side language, you literally have no way to edit your HTML without refreshing the page (using PHP). You can, however, accomplish such by using javascript and, for an even simpler usage, I would go with jQuery for such a case in order to extremely simplify the whole code. Please look at an example of api.jquery.com/jquery.ajax and configure your current index to perform an AJAX request to your metar.php script that is supposed, at this point, to return a value. Commented Jan 9, 2015 at 8:20
  • Not a big deal, we all have to start somewhere, but yes I would mind posting the code as this is something you can very easily find on the internet, were you using a javascript framework (jQuery for example) or Plain javascript. In both cases, we're talking about a 1 line code. Commented Jan 9, 2015 at 8:23
  • So would this work? <script type="text/javascript" src="./jquery-1.3.2.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#container-id-to-load-into').load('metar.php); }); </script> Commented Jan 9, 2015 at 8:26

1 Answer 1

3

This can be done using AJAX. Code bellow shows how it can be done using jQuery.

<div id="dectinationDivId" style="color: white;"></div>

<button id="buttonId" style="height: 40px;" class="btn btn-primary">METAR At London Heathrow</button>

<script src="http://code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $('#buttonId').click(function(){
        $.ajax({
            url: "/heathrow.php",
            success: function(data) {
                $('#dectinationDivId').html(data);
                $('#buttonId').hide();
            },
            error: function(jqXHR) {
                alert(jqXHR.responseText);
            }
        });
    });
</script>

For multiple buttons there is a better, more generic, approach which makes it easier to maintain code (add and remove buttons, in this case).

HTML/JS:

<script src="http://code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function() {
        var metarButtons = $('.getMetarButtons');
        metarButtons.click(function(){
            var clickedButton = $(this);
            $.ajax({
                type: "POST",
                url: "/metarData.php",
                data: { location: clickedButton.attr('data-location') },
                dataType: 'html',
                success: function(data) {

                    $('#outputDiv').hide('slow', function() {
                        $(this).remove();
                    });

                    metarButtons.show('slow');

                    var outputElement = $('<div id="outputDiv" style="color: white;">' + data + '</div>');
                    outputElement.hide();
                    outputElement.insertAfter(clickedButton);

                    clickedButton.hide('slow', function() {
                        outputElement.show('slow');
                    });
                },
                error: function(jqXHR) {
                    alert(jqXHR.responseText);
                }
            });
        });
    });
</script>

<button style="height: 40px;" class="btn btn-primary getMetarButtons" data-location = "LLBG">METAR At Tel Aviv Ben Gurion</button>
<button style="height: 40px;" class="btn btn-primary getMetarButtons" data-location = "EGLL">METAR At London Heathrow</button>
<button style="height: 40px;" class="btn btn-primary getMetarButtons" data-location = "EGGW">METAR At London Luton</button>
<button style="height: 40px;" class="btn btn-primary getMetarButtons" data-location = "KJFK">METAR At New York John F. Kennedy</button>

PHP (metarData.php):

<?php
    $location = $_POST["location"];

    get_metar($location);

    function get_metar($location) {
    $fileName = "http://weather.noaa.gov/pub/data/observations/metar/stations/$location.TXT";
        $metar = '';
        $fileData = @file($fileName) or die('METAR not available');
        if ($fileData != false) {
            list($i, $date) = each($fileData); 

                $utc = strtotime(trim($date));
                $time = date("D, F jS Y g:i A",$utc);

                while (list($i, $line) = each($fileData)) {
                    $metar .= ' ' . trim($line);
                }
            $metar = trim(str_replace('  ', ' ', $metar));
        }

        echo "METAR FOR $location (Issued: $time UTC):<br>$metar";
    }
?>
Sign up to request clarification or add additional context in comments.

12 Comments

@MažvydasTadaravičius Well, half works. See the website and try clicking the buttons. It seems only the top one works and then loads one of the four defined stations at random when it is clicked.
@TheoBearman - When selecting element by id, if there are multiple elements with the same id, only first one gets selected. In Your case, because You have 4 buttons, 4 unique ids have to be used. Or with some modification to PHP, JS and HTML, You can have 4 buttons with same class and location attribute which would get passed to PHP. This way, only one AJAX function would have to be declared.
@MažvydasTadaravičius I understand. I am currently in a lesson but I will assign each button a unique ID when I can. That should make it work yes?
@MažvydasTadaravičius Is it the buttonID or DivID I need to make unique or both?
@TheoBearman - If You use Copy/Paste approach, then both ids have to be unique, as well as JS code Copy/Pasted and changed accordingly. As I've mentioned previously, there is a better, more generic, approach. I've updated my answer to show it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.