Created
July 25, 2017 09:57
-
-
Save trieb/bb63d9a88246cead9e47de1b3e72f6ec to your computer and use it in GitHub Desktop.
Post data from javascript to php-script (example using api and data from openweathermap.org)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
</head> | |
<body> | |
<?php | |
// Now to something with the data (don't forget error checking and filtering...) | |
echo "<h4>Forecast</h4>"; | |
echo "City: " . $_POST['city'] . "<br>"; | |
echo $_POST['temp_day'] . ": " . $_POST['desc']; | |
?> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<title>WeatherApp</title> | |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> | |
</head> | |
<body> | |
<script> | |
$(document).ready(function(){ | |
$('#GetForecastButton').click(function(){ | |
GetForecast(); | |
}); | |
}); | |
</script> | |
<h4>Get weather forecast:</h4> | |
<form> | |
City: <input id="cityText" type="text" name="city" value="Motala"></select> | |
<input type="button" value="Get Forecast" id="GetForecastButton" > | |
</form> | |
<p><div id="weather"></div></p> | |
<script> | |
function GetForecast(){ | |
var city = $("#cityText").val(); | |
var numberOfDays = "1"; | |
var apiKey = "your_api_key"; | |
var url = "http://api.openweathermap.org/data/2.5/forecast/daily?q=" + city + "&units=metric&cnt=" + numberOfDays + "&APPID=" + apiKey | |
$.getJSON(url).then(function(data) { | |
console.log(data); | |
var description = data.list[0].weather[0].description; | |
var temperature_day = data.list[0].temp['day']; | |
// Print weather to the page in the div-section with id="weather" | |
$('#weather').text(temperature_day + ' deg C (' + description + ')'); | |
// Prepare data to be posted to php-script | |
var postData = | |
{ | |
"city":city, | |
"desc":description, | |
"temp_day":temperature_day, | |
}; | |
$.ajax({ | |
type: "POST", | |
url: "receive_forecast.php", | |
data: postData, | |
success: function(response){ | |
alert(response); // This is the response from receive_forecast.php | |
}, | |
error: function(e){ | |
console.log('Error: ' + e.message); | |
} | |
}); | |
}); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment