Documentation

Code Examples


Code examples for the area_code method in PHP and jQuery:

PHP


<?php
// Get text from query string or set to empty
$text = isset($_GET['text']) ? $_GET['text'] : '';

$url = 'https://api.t2a.io/rest/?'
. 'method=area_code'
. '&api_key=YOUR_API_KEY'
. '&text=' . urlencode($text);

// Fetch XML from T2A API
$result = simplexml_load_file($url);

if($result) {

  // Check for errors
  if($result->status == 'ok') {

    $area_code_list = $result->area_code_list;

  } else {

    // Report error
    echo 'Error: ' . $result->error_code;
    exit;

  }
}
?>

<!DOCTYPE html> 
<html lang="en"> 
  <head> 
    <meta charset="UTF-8"> 
    <title>Code example</title>
  </head>
  <body>
    <!-- iterate over list of area codes -->
    <?php foreach($area_code_list->area_code as $area_code): ?>
    <!-- output area code -->
    <h2><?php echo $area_code->code; ?></h2>
    <ul>
      <!-- iterate over list of places in this area code -->
      <?php foreach($area_code->place_list->place as $place): ?>
      <!-- output place name -->
      <li><?php echo $place->name; ?></li>
      <?php endforeach; ?>
    </ul>
    <?php endforeach; ?>
  </body>
</html>                 
	
	

jQuery


<!DOCTYPE html> 
<html lang="en"> 
  <head> 
    <meta charset="UTF-8"> 
    <title>Code example</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>

    <script type="text/javascript">
    $(document).ready(function(){ 

      // Attach code to form's onsubmit event
      $(".demo").submit(function() {

        // Fetch JSON from T2A API
        $.getJSON("https://api.t2a.io/rest/?callback=?",
        { 
          "method" : "area_code",
          "api_key" : "YOUR_API_KEY", // better to use js_key obtained from javascript_key service for security reasons
          "output" : "json",
          "text" : $("#text").val()
        },
        // Function to parse resulting JSON
        function(result) {

        // Check for errors
          if(result.status == "ok") {

            var html = "<p><strong>Your search returned the following dialling codes:</strong></p>";
            $.each(result.area_code_list, function() {
              html += "<h2>" + this.code + "</h2><ul>";
              $.each(this.place_list, function() {
                html += "<li>" + this.name + "</li>";
              });
              html += "</ul>";
            });
            $("#results").html(html);

          } else {
            // report error
            alert("Error: " + result.error_code);
          }

        }
	    );

        return false;
      });
    });
    </script>

  </head>
  <body>
    <form class="demo">
      <label for="text">Dialling code, location, or postal area:</label>
      <input type="text" id="text" />
      <input type="submit" />
    </form>
    <div id="results"></div>
  </body>
</html>