Issues integrating response from OpenWeatherMap in to my HTML - javascript

I'm using the OpenWeatherMap API to get to display certain items in HTML and my code does not display them.
$('.`btn`').click(function() {
var city = $('.inputValue').val();
var key = '88da1611665dfe9338cd6679dee95466';
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather',
dataType: 'json',
type: 'GET',
data: {
q: city,
appid: key,
units: 'metric'
},
success: function(data) {
var temp = '';
$.each(data.weather, function(index, val) {
wf += '<p><b>' + data.name + "</b><img src=" + val.icon + ".png></p>" +
data.main.temp + '°F ' + ' | ' + val.main + ", " +
val.humidity + val.wind + val.uv
}, $("showWeather").html(temp));
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="4">
<nav class="navbar navbar-light bg-light">
<p><b>Search for a city:</p></b>
<form class="d-flex">
<input type="search" class="inputValue" placeholder="" aria-label="Search">
<button class="btn btn-outline-success">
<i class="fas fa-search"></i>
</button>
</form>
</nav>
</div>
</div>
<div class="col-8">
<div class="row">
<h2 id="showWeather" class="date"></h2>
<p>Temperature:</p>
<p>Humidity:</p>
<p>Wind Speed:</p>
<p>UV Index:</p>
</div>
</div>
</div>

There's quite a few individual issues in your code:
You have backticks in the .btn selector which are invalid, remove them.
You need to prevent the standard form submission so that the AJAX call can fire and return data without the page refreshing. To do this call preventDefault() on the event which is fired, ideally on the submit of the form, not click of .btn.
</p></b> tags are the wrong way around
.html(temp) needs to be placed outside the each(), and definitely not as an additional argument passed to it
wf += should be temp += as that's what your variable is called
You can use map() along with template literals to build the HTML string more succinctly.
You're missing the # on $('showWeather')
wind is an object so you can't concatenate it to the string directly. Access its speed or deg properties (or both).
humidity is a property of main, not the weather you're looping through
There is no uv property anywhere in the response, so that needs to be removed.
With all that fixed, try this:
$('.d-flex').on('submit', function(e) {
e.preventDefault();
var city = $('.inputValue').val();
var key = '88da1611665dfe9338cd6679dee95466';
$.ajax({
url: 'https://api.openweathermap.org/data/2.5/weather',
dataType: 'json',
type: 'GET',
data: {
q: city,
appid: key,
units: 'metric'
},
success: function(data) {
let html = data.weather.map(loc => `<p><b>${data.name}</b><img src="${loc.icon}.png" /></p>${data.main.temp}°F | ${loc.main}, ${data.main.humidity}%, ${data.wind.speed}kph # ${data.wind.deg}°`);
$("#showWeather").html(html);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="4">
<nav class="navbar navbar-light bg-light">
<p><b>Search for a city:</b></p>
<form class="d-flex">
<input type="search" class="inputValue" placeholder="" aria-label="Search" value="miami">
<button class="btn btn-outline-success">
Search
<i class="fas fa-search"></i>
</button>
</form>
</nav>
</div>
</div>
<div class="col-8">
<div class="row">
<h2 id="showWeather" class="date"></h2>
<p>Temperature:</p>
<p>Humidity:</p>
<p>Wind Speed:</p>
<p>UV Index:</p>
</div>
</div>
</div>

Related

How to Populate HTML with data from jquery (multiple nested div)

I want to Populate elements inside class info-wrapper using JQuery.
Data that has to populate are inside data variable in JQuery.
I can't use $('#id').append("div") like these syntax because i want to nest multiple div inside each other and popluate .card-wrapper and its child elements for every data item.
Jquery
$.ajax({
method: 'GET',
url: 'getUser/admin',
dataType: 'json',
success: function (data) {
console.log(typeof(data));
data = Object.entries(data);
for(var i = 0;i<data.length;i++)
{
}
},
error: function () {
}
})
Blade Template
#extends('layouts.app')
#section('admin-content')
<div class="container">
<div class="row" id="inject">
<div class="col-md-6 col-sm-12">
<div class="card-wrapper">
<div class="info-wrapper">
<h2 id="name"></h2>
<h6 id="email"></h6>
<hr/>
<h6 id="department"></h6>
<h6 is="sem"></h6>
</div>
<div class="button-wrapper">
<button class="btn btn-danger" type="submit">Delete Account</button>
<button class="btn btn-secondary" type="submit">Block Account</button>
</div>
</div>
</div>
</div>
</div>
#endsection
Because info-wrapper is just a single element, you can instead populate elements inside the div with inject id, you can make changes to your js to generate elements dynamically, I hope this can help.
$.ajax({
method: 'GET',
url: 'getUser/admin',
dataType: 'json',
success: function (data) {
console.log(typeof(data));
data = Object.entries(data);
let html = '';
for(var i = 0;i<data.length;i++)
{
html += `
<div class="card-wrapper">
<div class="info-wrapper">
<h2 id="name">${data[i].name}</h2>
<h6 id="email">${data[i].email}</h6>
<hr/>
<h6 id="department">${data[i].department}</h6>
<h6 is="sem"><${data[i].sem}/h6>
</div>
<div class="button-wrapper">
<button class="btn btn-danger" type="submit">Delete Account</button>
<button class="btn btn-secondary" type="submit">Block Account</button>
</div>
</div>
`;
}
html = `<div class="col-md-6 col-sm-12">${html}</div>`
$('#inject').html(html);
},
error: function () {
}
})

How to identify multiple forms in one template?

I'm trying to implement a follower/following system in Django. In the template, all follow requests have a user and they all have user id's that can be displayed. The template is a profile page that contains several follow requests made by other users. I have created a separate form for each accept/decline and I want to uniquely identify each form so that I can submit that one and remove it subsequently.
<div class="col s12 l6 trending-panel container">
<h4>
Requests
</h4>
<div class="divider"></div>
{% for bond_request in bond_requests %}
{% if bond_request.accepted == False %}
<div>
<div class="row bond-request-row" id="{{bond_request.by_user.id}}">
<div class="col s6">
<a href="{% url 'accounts:profile' bond_request.by_user.username %}">
<div class="col s8">
<img class="profile-image-request" src="https://m.media-amazon.com/images/M/MV5BNjUxNDcwMTg4Ml5BMl5BanBnXkFtZTcwMjU4NDYyOA##._V1_.jpg" alt="">
</div>
<div class="col s4">
<h6 id="follower-username">
#{{bond_request.by_user}}
</h6>
</div>
</a>
</div>
<div class=" col s12 center accept-decline-margin">
<div class="col s12 l6">
<form action="accounts:accept_bond_request" method="POST" id="bond-request-accept-form">
<!-- <a href="#" id="bond-request-accept" class="green-text white btn">
<div>
<ion-icon name="add"></ion-icon>
<span>Accept</span>
</div>
</a> -->
<button id="bond-request-accept" class="green-text white btn" type="submit">Accept</button>
</form>
</div>
<div class="col s12 l6">
<a href="" class="grey-text white btn">
<div class="">
<ion-icon name="remove"></ion-icon>
<span>Ignore</span>
</div>
</a>
</div>
</div>
</div>
<!-- HERE -->
</div>
{% else %}
{% endif %}
<div class="divider">
</div>
{% endfor %}
</div>
$("#bond-request-accept-form").on('submit',function(){
// Cleans the username
// var each_bond_request = $();
var raw_follower_username = $("#follower-username").text().trim();
var follower_username = raw_follower_username.replace("#","");
console.log("Follower username: ",follower_username);
$.ajax({
type: "POST",
url: "/accounts/user/" + follower_username + "/accept_request",
data:{
"follower_username" : follower_username,
},
success: function(data){
console.log(data);
M.toast({html: follower_username + ' started following you',classes: 'green'}, );
},
error: function(data){
console.log("All error data: ",data);
M.toast({html: 'Failure',classes: 'red'}, );
},
});
});
You should create a standalone function to handle submit. And reference this function in each form you created.
function SubmitHandler (e) {
// Cleans the username
// var each_bond_request = $();
var raw_follower_username = $(e).find("#follower-username").text().trim();
var follower_username = raw_follower_username.replace("#","");
console.log("Follower username: ",follower_username);
$.ajax({
type: "POST",
url: "/accounts/user/" + follower_username + "/accept_request",
data:{
"follower_username" : follower_username,
},
success: function(data){
console.log(data);
M.toast({html: follower_username + ' started following you',classes: 'green'}, );
},
error: function(data){
console.log("All error data: ",data);
M.toast({html: 'Failure',classes: 'red'}, );
},
});
return false;
}
Then in your template:
...
<form id="bond-request-accept-form" onsubmit="SubmitHandler(this)">
...
Note the #follower-username should be nested within the form tag for jQuery to find the correct one.
First, I just want to say that I may be understanding your question wrong. If so, feel free to correct me.
If I am understanding this right, you have multiple copies of essentially the same form with slight variations depending on the user that is sending the request. Since IDs are meant to be unique and can cause issues in JavaScript if there are more than one instance of them, I would change the bond-request-accept-form to a class rather than an ID, and do something like this in JQuery:
$(".bond-request-accept-form").toArray().forEach(function(elem){
$(elem).on('submit', function(){
// Logic to perform when the form is submitted
});
});
Put different URLs in the action for the two forms. Then you'll have two different view functions to deal with the two different forms.

Alpacajs form data not submitting if user does not tab off textbox

I am having an issue with alpacajs form not submitting data from a textbox if the user does not tab off the textbox before clicking the submit button, if the user has 5 fields to fill out all but the last one is included in the json results.
<div class="panel-group" id="accordian" role="tablist">
<div class="panel-placeholder"></div>
</div>
<div>
<button class="btn btn-default" type="submit">Submit</button>
</div>
<script id="panel-template" type="text/x-handlebars-template">
{{#each panels}}
<div class="panel panel-primary">
<div class="panel-heading">
<h4 class="panel-title">
<a role="button" data-toggle="collapse" data-parent="#accordion" href="#{{panelId}}">
{{title}}
</a>
</h4>
</div>
<div id="{{panelId}}" class="panel-collapse collapse in">
<div class="panel-body">
{{#each sections}}
<div id={{formId}}></div>
{{/each}}
</div>
</div>
</div>
{{/each}}
</script>
and the js code
function onData(formData) {
var friendlyData = "";
// Grab the template script
var templateScript = $("#panel-template").html();
// Compile the template
var compiledTemplate = Handlebars.compile(templateScript);
var compiledHtml = compiledTemplate(formData);
// Add the compiled html to the page
$('.panel-placeholder').html(compiledHtml);
//submit all data
$("[type='submit']").click(function () {
var postData = {
data: JSON.stringify(formData),
friendlyData: friendlyData,
storeData: storeData,
origUrl: origUrl
}
$.ajax({
url: apiUrl + "submit/",
data: postData,
dataType: 'json',
type: 'POST',
success: function (data) {
alert("Data was saved");
},
error: function (err) {
alert(err.statusText);
}
});
});
}
Any help with this would be great, I have not been able to find a solution.
Thank you

i want to associate links to respective article on dynamically created p element

here is my codepen link
my html code
<div id="main">
<h1>Wikipedia Viewer</h1>
<form class="form-inline">
<div class="container">
<div class="row">
<div class="col-sm-6 col-sm-offset-4 col-lg-7 col-lg-offset-4">
<div class="form-group">
<label class="sr-only" for="search">search</label>
<input type="text" class="form-control" placeholder="Search">
</div>
<button type="button" class="btn btn-primary"><i class="fa fa-search"></i></button></form>
</div>
</div>
</div>
Surprise me!
</div>
<div id="search">
</search>
jquery code for making wikipedia api search call and then displaying title and overview.i want to associate links to respective article on dynamically created p element
$(document).ready(function() {
$("button").click(function() {
var article = $("input").val();
$.ajax({ //wikipedia api call
url: "https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=" + article + "&format=json",
dataType: "jsonp",
success: function(data) {
for (var i = 0; i < data.query.search.length; i++) { //displaying titles and snippets accroding to search query. i want to associate link to each dynamically created p element.
var title = data.query.search[i].title;
var snippet = data.query.search[i].snippet;
$("#search").append("<p>" + title + "<br>" + snippet + "</p>");
}
$("#main").attr({
'style': 'display: none'
});
},
error: function() {
$("h1").html("oops");
}
});
});
});
Change your $("#search").append() as follows:
$("#search")
.append("<p><a href='https://en.wikipedia.org/wiki/" + title + "'>" + title + "</a>" +
"<br>" + snippet + "</p>"
);
Codepen

jQuery remove class on closest

I'm trying to action a removeClass request using jQuery. Most of the below script is working fine except for the $(this).closest('.press-continue').removeClass('hidden'); part.
I have posted the jQuery and HTML below. Any ideas what could be the problem?
$(function () {
$('.step2').on('click', '.btn-book', function (e) {
$.ajax({
url: '/reserve/' + this.id,
type: 'get',
dataType: 'json',
context: this,
success: function (json) {
if (json['success']) {
$(this).addClass('btn-selected');
$('.btn-book').not(this).addClass('book-disabled').prop('disabled', true);
$('.next-step-hidden').addClass('show-button').prop('href', '/confirm/' + this.id);
$('.cancel').addClass('show-button').prop('id', this.id);
$('.alert-danger').addClass('hidden-error');
$(this).closest('.press-continue').removeClass('hidden');
} else if (json['error']) {
if (json['error'] == 1) {
alert("Another user has already booked this slot, please choose another slot.");
$(this).addClass('btn-selected').addClass('book-disabled').prop('disabled', true);
}
}
}
});
});
});
HTML
<div id="main">
<h2 class="info-bar clearfix"><b>Select parking time</b> <span>Step <i>2</i></span></h2>
<div class="alert alert-danger hidden-error">
<strong>Expired!</strong> Sorry, the slot that you reserved has now expired. Please choose another slot below.
<br><i>Note: slots are reserved for 15 minutes.</i>
</div>
<form class="step2">
<fieldset>
<legend><span>Select a Parking Slot</span></legend>
<div class="parking-time">
<div class="input-row">
<label class="label">12/06/2015
<br>Morning
<br>7am - 1pm</label>
<button class="btn btn-small btn-important btn-book" type="button" id="67"><i>book</i><b>reserved</b></button>
<span class="press-continue hidden">Press continue to confirm booking</span>
</div>
<div class="input-row">
<label class="label">12/06/2015
<br>Afternoon
<br>2pm - 7pm</label>
<button class="btn btn-small btn-important btn-book" type="button" id="68"><i>book</i><b>reserved</b></button>
<span class="press-continue hidden">Press continue to confirm booking</span>
</div>
<div class="input-row">
<label class="label">12/06/2015
<br>All Day
<br> </label>
<button class="btn btn-small btn-important btn-book" type="button" id="69"><i>book</i><b>reserved</b></button>
<span class="press-continue hidden">Press continue to confirm booking</span>
</div>
</div>
<!-- end parking-time -->
<div class="input-row input-row-last"> <a class="btn btn-small btn-info cancel">Cancel</a> <a class="btn btn-info next-step next-step-hidden">Continue <i class="sprite arrow"></i></a> </div>
</fieldset>
</form>
</div>
<!-- end main -->
.closest() is used to find an ancestor element, where as what you are looking for is the next sibling so you can use .next()$(this).next('.press-continue').removeClass('hidden');
$(function () {
$('.step2').on('click', '.btn-book', function (e) {
$.ajax({
url: '/reserve/' + this.id,
type: 'get',
dataType: 'json',
context: this,
success: function (json) {
if (json['success']) {
$(this).addClass('btn-selected');
$('.btn-book').not(this).addClass('book-disabled').prop('disabled', true);
$('.next-step-hidden').addClass('show-button').prop('href', '/confirm/' + this.id);
$('.cancel').addClass('show-button').prop('id', this.id);
$('.alert-danger').addClass('hidden-error');
$(this).next('.press-continue').removeClass('hidden');
} else if (json['error']) {
if (json['error'] == 1) {
alert("Another user has already booked this slot, please choose another slot.");
$(this).addClass('btn-selected').addClass('book-disabled').prop('disabled', true);
}
}
}
});
});
});

Categories

Resources