Reputation: 93
I am making a weather app and want my weather data to open on new page but it's currently opening underneath the search bar. I want it to redirect to another HTML-page with the weather data from the Javascript code when I push the search-button. How do I do that the easiest way?
This is my Javascript code that gets the weather data: $(function() {
$("#city-form").on('submit', function(e){
e.preventDefault();
e.returnValue = false;
search($("#city-input").val());
});
function search(city){
$("#city").html("");
$("#description").html("");
$("#temp").html("");
$("#humidity").html("");
$("#wind").html("");
var query = {
'q' : city,
'lang': 'SE',
'units': 'metric',
'APPID' : '31fb7e0aa1f90896809571484a8b13cc'
};
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather",
type: 'get',
async: true,
contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
dataType: "json",
data: query,
error: function (request, status, error) {
alert(JSON.parse(request.responseText).message);
console.log(request.responseText);
},
success: function (data) {
// Logs server reseponse
console.log(JSON.stringify(data));
// Sends data for presentation
present(city, data);
}
});
}
function present(city, data){
$("#city").html(city);
$.each(data.weather, function(i, weather) {
$("#description").append("<img class='w-icon' src='http://openweathermap.org/img/w/" + weather.icon + ".png' />");
$("#description").append(weather.description + " ");
});
$("#temp").html(data.main.temp + " °C");
$("#humidity").html("Luftfuktighet: "+ data.main.humidity + "%");
$("#wind").html("Vind: "+ data.wind.speed + " m/s");
}
});
And this is my HTML-code with the search bar and weather data:
<form id="city-form">
<input type="text" id="city-input" class="form-control" placeholder="Sök på stad" required>
<button type="submit" id="submit-btn" class="btn btn-primary">Sök</button>
<input type="reset" value="Reset">
</form>
<div id="weather">
<div id="city"></div>
<div id="temp"></div>
<div id="description"></div>
<div id="humidity"></div>
<div id="wind"></div>
</div>
Upvotes: 1
Views: 497
Reputation: 978
I recomend you create another page that receives the city as a query param.
myPage?city="london"
Code for redirect:
function search(city){
window.location.href = 'myPage?city=' + city
}
If you prefer open in a new tab: Open a URL in a new tab (and not a new window) using JavaScript
On the new page you recover the city from params How to get the value from the GET parameters?
And do the ajax request the same way you do now, you gonna move the display info to the new page:
<div id="weather">
<div id="city"></div>
<div id="temp"></div>
<div id="description"></div>
<div id="humidity"></div>
<div id="wind"></div>
Upvotes: 1