How to make a call about an API response

Asked

Viewed 213 times

0

I’m working on this codepen. My goal is to create variable responses according to the temperature and climate of the place. Example: Clear sky and neighborhood 1 is answer X, rain and neighborhood 2 is answer Y. I am learning PHP, however I would like to vary this answer according to API response. It follows code below. (In the "Clear Sky" example, the answer comes as "Clear Sky" and the code modifies.

var weatherData = {
  city: document.querySelector ("#city"),
  weather: document.querySelector ("#weather"),
  temperature: document.querySelector("#temperature"),
  temperatureValue: 0,
  units: "°C"
  
};

function roundTemperature(temperature){
			temperature = temperature.toFixed(1);
			return temperature;
		}

function switchUnits (){
  
  if (weatherData.units == "°C") {
    weatherData.temperatureValue = roundTemperature(weatherData.temperatureValue * 9/5 + 32);
    weatherData.units = "°F";
  
} else {
  weatherData.temperatureValue = roundTemperature ((weatherData.temperatureValue -32) * 5/9);
    weatherData.units = "°C";  
}

  weatherData.temperature.innerHTML = weatherData.temperatureValue + weatherData.units + " ";
}


function getLocationAndWeather(){
  if (window.XMLHttpRequest){
    var xhr = new XMLHttpRequest();
    xhr.addEventListener("load", function() {
      var response = JSON.parse(xhr.responseText);

      console.log(response);
      var position = {
        latitude: response.latitude,
        longitude: response.longitude
      };
      var cityName = response.city;

      var weatherSimpleDescription = response.weather.simple;
      var weatherDescription = translateDescription(response.weather.description);
      var weatherTemperature = roundTemperature(response.weather.temperature);

      weatherData.temperatureValue = weatherTemperature;

      loadBackground(position.latitude, position.longitude, weatherSimpleDescription);
      weatherData.city.innerHTML = cityName;
      weatherData.weather.innerHTML =  ", " + weatherDescription;
      weatherData.temperature.innerHTML = weatherTemperature + weatherData.units;
    }, false);

    xhr.addEventListener("error", function(err){
      alert("Could not complete the request");
    }, false);

    xhr.open("GET", "https://fourtonfish.com/tutorials/weather-web-app/getlocationandweather.php?owapikey=e2db5b0453a25a492e87ad8b03046a7c&units=metric", true);
    xhr.send();
  }
  else{
    alert("Unable to fetch the location and weather data.");
  }           
}


function loadBackground(lat, lon, weatherTag) {
  var script_element = document.createElement('script');

  script_element.src = "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=1452866c8cea54acd0075022ef573a07&lat=" + lat + "&lon=" + lon + "&accuracy=1&tags=" + weatherTag + "&sort=relevance&extras=url_l&format=json";
  
  document.getElementsByTagName('head')[0].appendChild(script_element);
}

function jsonFlickrApi(data){
  if (data.photos.pages > 0){
    //var randomPhotoId = parseInt(data.photos.total);
    var photo = data.photos.photo[Math.floor(Math.random()*parseInt(data.photos.photo.length))];
    document.querySelector("body").style.backgroundImage = "url('" + photo.url_l + "')";
    document.querySelector("#image-source").setAttribute("href", "http://www.flickr.com/photos/" + photo.owner + "/" + photo.id);
  }
  else{
    document.querySelector("body").style.backgroundImage = "url('https://fourtonfish.com/tutorials/weather-web-app/images/default.jpg')";
    document.querySelector("#image-source").setAttribute("href", "https://www.flickr.com/photos/superfamous/310185523/sizes/o/");
  }
}

function translateDescription(description) {
    var xhttp = new XMLHttpRequest();
    xhttp.open("GET", "https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=pt&dt=t&q=" + description, false);
    xhttp.send();
    var response = JSON.parse(xhttp.responseText);
    return response[0][0][0];
}

getLocationAndWeather();
body {
  height: 100%;
  margin: 0;
  padding: 0;
  font-family:Arial, sans-serif;
  font-size: 2em;
  text-shadow: 0 0 10px #000;
  color: #fff;
  background: #888;
  bacground-repeat: no-repeat;
  background-attachment: fixed;
  background-size: cover;
}

section {

   min-height: 100%;
}

h1 {
    font-size: 2em;
  padding: 0 0.3em;
  line-height: 1em;
  
}

p {
  padding: 0 1em;
}

a{
  color: #fff;
}

footer {
  position: absolute;
  bottom: 0;
  font-size: 0.5em;
}

#temperature {
   text-decoration: none;
  border-bottom: 0.05em dotted white;
}
<section>
  <h1 id= "city">Weather Web App</h1>
  <p> <a id="temperature" href="#" onclick="switchUnits(); return false;" title ="Click to switch between metric and impreial units"></a><span id = "weather"> by Shazam (tutorial from @fourtonfish)</p>
</section>

<footer>
  <p>Powered by <a href="http://flickr.com/services/api/">Flickr</a> and <a href="http://openweathermap.org">Openweathermap.org</a>.
    
  Created by <a href="https://twitter.com/steelcitycoach">@steelcitycoach</a>. <a id="image-source" href="#">Image source</a>.</p>
  
</footer>

So I think it’s easy: I need to put a variable in the answer. I imagine it was something like this: (I wonder if I should use two quotation marks (") and not just a quotation mark (') ?

<?php
if ($resultado1 = 'clear sky') {
  echo "Resposta 1";

}
?>

Now I’m having trouble transferring the javascript variable to php. I’ve turned index.html into index.php. Below, I created what I believe would make sense, but the result does not appear on the screen.

	<?php 
  $variavelphp = "<script>document.write(weatherDescription)</script>";


if ($variavelphp == 'clear sky') {
    echo "Resposta 1";    
}
 ?>

1 answer

0

The Open Weather Map API supports multilingualism, which in this case would be for Portuguese.

Since the Portuguese offered is not specific to Brazil (probably that of Portugal), you would have to do your own translation.

Being the return via javascript, you could do it via javascript or send it to PHP (via ajax) and return only the translation.

From any furnace, the result returned by the API is a JSON and you need to treat it as such.

JSON

In javascript:

//string retornada no meu teste
var string = '{"latitude":-29.1878,"longitude":-51.3402,"city":"Farroupilha","weather":{"simple":"Clouds","description":"few clouds","temperature":21.3},"source":"smart-ip.net, openweathermap.org"}';
    
var json = JSON.parse(string);
    
console.log(json.weather.description);

Already in PHP

$string = '{"latitude":-29.1878,"longitude":-51.3402,"city":"Farroupilha","weather":{"simple":"Clouds","description":"few clouds","temperature":21.3},"source":"smart-ip.net, openweathermap.org"}';

$json = json_decode($string);

echo ($json->weather->description);

For both examples, the output is the same:

few Clouds

Validation/Comparison

As for the comparison, well, your code has an error only, you are comparing using only one equal (=). An equal means attribution. For comparison, two:

if ($resultado1 == 'clear sky') {
    echo "Resposta 1";    
}

Strings

Should I use two quotation marks (") and not just a quotation mark (') ?

In your case, single or double quotes are irrelevant.

Double quotes, in a string, will perform variable interpolation. That is, the variables will be interpreted as variables and, the string, will use the value that the variable has.

On the other hand, single quotes will not interpolate variables. That is, everything in the string will only be treated as a string. See the example:

$s = "dollars";
echo 'This costs a lot of $s.'; // This costs a lot of $s.
echo "This costs a lot of $s."; // This costs a lot of dollars.

You can check that in the first echo the result is $s and in the second is dollars.

More information can be found on manual

  • I understood, but I still have a question. I edited my answer in the footer, if you can take a look I thank Gabriel! I’m experiencing this error: Parse error: syntax error, Unexpected '$variavelphp' (T_VARIABLE) in C: xampp2 htdocs one homedir public_html temperature index.php on line 47

  • @Pedrogusmão Javascript does not communicate directly with PHP (not the way you are trying). You have to make a call via ajax. Your mistake, however, is not in the code you reported, there is more behind. Please see the following link to send the result to PHP: https://answall.com/a/25215/5007

  • I read and understood Gabriel, but unfortunately I don’t have this knowledge of AJAX to do this. I believe you understand what I’m trying to do, but in ajax I couldn’t do it, but thank you!

  • @Pedrogushand in this case, you can do everything directly in javascript. It would be very similar to PHP.

  • I’ll try this way then! My goal is just to vary the result even, example: Is it raining? Stay home! Is it sunny? Go out to the street!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.