When 5 cards are created for the 5-day weather forecast, the icon, temp, and humidity data are correct, but the date stays the same on all five cards. Any idea why? Thank you!
UPDATE: I added "if-sentence" realizing that the data I get is for every few hours so that`s the reason my cards all have the same date. This syntax seems logical to me, but it ends up giving me only one card. I hope someone can spot the error in my code. Thank you.
$(document).ready(function() {
$("#submit").on("click", function() {
var userInput = $("#user-input").val();
fiveDayForecast(userInput);
});
var key = 'my API key';
var url = "https://api.openweathermap.org/data/2.5/forecast";
function fiveDayForecast(userInput) {
$.ajax({
url: url,
dataType: "json",
type: "GET",
data: {
q: userInput,
appid: key,
units: "imperial",
cnt: "5"
},
success: function(data) {
$("#five-day-forecast").empty();
for (var i = 0; i < data.list.length; i++) {
if(data.list[i].dt_txt.indexOf("15:00:00") !== -1) {
var colEl = $("<div>").addClass("col col-lg-2");
var cardEl = $("<div>").addClass("card text-white bg-primary m-3");
var cardBody = $("<div>").addClass("card-body");
var cardTitle = $("<h5>").addClass("card-title").text(new Date(data.list[i].dt_txt).toLocaleDateString());
var img = $("<img>").attr("src", "http://openweathermap.org/img/w/" + data.list[i].weather[0].icon + ".png");
var cardText1 = $("<p>").addClass("card-text").text("Temp: " + data.list[i].main.temp_max + " °F");
var cardText2 = $("<p>").addClass("card-text").text("Humidity: " + data.list[i].main.humidity + "%");
colEl.append(cardEl.append(cardBody.append(cardTitle, img, cardText1, cardText2)));
$("#five-day-forecast").append(cardEl);
}
}
}
})
}
});
Sample data:
"list":[
{ "dt":1595840400, "main":{}, "weather":[], "clouds":{}, "wind":{}, "visibility":10000, "pop":0.66, "rain":{},
"sys":{}, "dt_txt":"2020-07-27 09:00:00"
},
...
]
Related
I am trying to display several images(PrinurlonPage) that are contained in an array and also position them on the page randomly. I have two issues,
The first and most important is that I cant get the images to display on IE when I look the source attribute on developer tools I just see undefined whereas in chrome I get the full URL that was passed. I was wondering if there was something wrong with the order in which the script was being run that was causing the problem.
The second question is about positioning the images randomly on the page and also prevent overlapping, I would like to know how can I achieve this, what I have implemented at the moment in some iterations the pictures overlap.
I would appreciate any suggestion on this
var getIndividualPersonDetails = function(GetPictureUrl, printurlonPage, getRandom) {
listName = 'TeamInfo';
var PeopleCompleteList = [];
var personName, userName, UserTitle, UserphoneNumber, UserEmail, Id, myuserPicture;
// execute AJAX request
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items?$select=Name/Title,Name/Name,Name/Id,Name/EMail,Name/WorkPhone&$expand=Name/Id",
type: "GET",
headers: {
"ACCEPT": "application/json;odata=verbose"
},
success: function(data) {
for (i = 0; i < data.d.results.length; i++) {
//check if the user exists if he does store the following properties name,title,workphone,email and picture url
if (data.d.results[i]['Name'] != null) {
personName = data.d.results[i]['Name'].Name.split('|')[2];
userName = data.d.results[i]['Name']['Name'];
UserTitle = data.d.results[i]['Name']['Title'];
UserphoneNumber = data.d.results[i]['Name']['WorkPhone'];
UserEmail = data.d.results[i]['Name']['EMail'];
Id = data.d.results[i]['Name']['Id'];
myuserPicture = GetPictureUrl(userName);
PeopleCompleteList.push(PersonConstructor(personName, UserTitle, UserphoneNumber, UserEmail, myuserPicture, Id));
}
}
PeopleObject = PeopleCompleteList;
PrinturlonPage(PeopleCompleteList, getRandom);
},
error: function() {
alert("Failed to get details");
}
});
}
//print all the image links in the peopleCompleteList array and then position them randomly on the page
var PrinturlonPage = function(PeopleCompleteList, getRandom) {
var imageList = [];
for (i = 0; i < PeopleCompleteList.length; i++) {
var top = getRandom(0, 400);
var left = getRandom(0, 400);
var right = getRandom(0, 400);
imageList.push('<img style="top:' + top + ';right:' + right + '" id="image' + PeopleCompleteList[i]['UserId'] + '" alt="' + PeopleCompleteList[i]['Title'] + '"class="imgCircle" src="' + PeopleCompleteList[i]['Picture'] + '"/>');
//imageList +='<img class="img-circle" src="'+PeopleCompleteList[i]['Picture']+ '"/>'
}
var imagesString = imageList.join().replace(/,/g, "");
$('#imageList').append(imagesString);
}
//funtion retrieves the picture
function GetPictureUrl(user) {
var userPicture="";
var imageurls="";
var requestUri = _spPageContextInfo.webAbsoluteUrl +
"/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=#v)?#v='"+encodeURIComponent(user)+"'";
$.ajax({
url: requestUri,
type: "GET",
async:false,
headers: { "ACCEPT": "application/json;odata=verbose" },
success: function (data) {
console.log(data);
var loginName = data.d.AccountName.split('|')[2];
console.log(loginName);
var PictureDetails = data.d.PictureUrl != null ? data.d.PictureUrl : 'https://xxxcompany/User%20Photos/Profile%20Pictures/zac_MThumb.jpg?t=63591736810';
imageurls = data.d.PersonalSiteHostUrl+'_layouts/15/userphoto.aspx?accountname='+ loginName+ '&size=M&url=' + data.d.PictureUrl;
userPicture1=imageurls;
}
});
return userPicture1;
}
var getRandom = function(x, y) {
return Math.floor(Math.random() * (y - x)) + x + 'px';
};
$(function() {
getIndividualPersonDetails(GetPictureUrl, PrinturlonPage, getRandom);
$(document).on('click', '.imgCircle', function() {
var theName = jQuery(this).attr('Id');
pullUserObject(theName);
//console.log(theId);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="imageList"></div>
I need to figure out how to have a link that I pull from a JSON object an ACTUAL link that the user can click and follow to the site instead of just text. I feel like it's gotta be a quick fix, but I can't seem to figure it out! Thanks for the help!!
function sqoot(URL) {
$.ajax({
url: URL,
method: "GET"
}).done(function(response) {
var deals = response.deals
var untrackedURL = $("#untrackedURL");
var couponInfo = $("#info");
for (i = 0; i < deals.length; i++) {
var newUntrackedURL = $("<a href='deals[i].deal.untracked_url'>" + deals[i].deal.untracked_url + "</a>");
couponInfo.append(newUntrackedURL)
}
})
};
Assuming your fetched data is correctly used, here's why your link doesn't work : the href is actually deals[i].deal.untracked_url instead of its content.
try this instead :
function sqoot(URL) {
$.ajax({
url: URL,
method: "GET"
}).done(function (response) {
var deals = response.deals
var untrackedURL = $("#untrackedURL");
var couponInfo = $("#info");
for (i = 0; i < deals.length; i++) {
var newUntrackedURL = $('' + deals[i].deal.untracked_url + "");
couponInfo.append(newUntrackedURL)
}
})
};
Without the generated JSON, I can't help you further if this solution doesn't helps.
Look like maybe you had a typo:
'deals[i].deal.untracked_url' should be 'deals["+ i +"].deal.untracked_url'
function sqoot(URL) {
$.ajax({
url: URL,
method: "GET"
}).done(function (response) {
var deals = response.deals
var untrackedURL = $("#untrackedURL");
var couponInfo = $("#info");
for (i = 0; i < deals.length; i++) {
var newUntrackedURL = $("<a href='deals["+ i +"].deal.untracked_url'>" +
deals[i].deal.untracked_url + "</a>");
couponInfo.append(newUntrackedURL)
}
});
Scratch that - you want it to pull the value not write out "deals[i].deal.untracked_url." To do that you do the below.
function sqoot(URL) {
$.ajax({
url: URL,
method: "GET"
}).done(function (response) {
var deals = response.deals
var untrackedURL = $("#untrackedURL");
var couponInfo = $("#info");
for (i = 0; i < deals.length; i++) {
var newUntrackedURL = $("<a href='"+deals[i].deal.untracked_url+"'>" +
deals[i].deal.untracked_url + "</a>");
couponInfo.append(newUntrackedURL)
}
});
I have this small script (fiddle) in charged for reading some blog XML. The problem is that it simply stopped working a few days ago. It seems the Ajax function is always returning null, even though there is data in the specified URL.
<script>
var toType = function(obj) {
return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
var buildRSS = function (container_id){
$.ajax({
type: "GET",
url: "http://bloginstructions.blogspot.dk/rss.xml",
dataType: "xml",
success: function(result){
var values = getEntries(result)
console.log(result)
for (var i = 0; i < 10; i++) {
var entry = values[i],
info = entry.__text.split("\n"),
title = info[0],
link = info[1],
date = entry.pubdate.match(/(.*) \d/)[1],
snippet = entry.description.replace(/<\/?[^>]+(>|$)/g, "").substring(0,350)+'...';
var html = '<div><h4>' + title + '</h4><p>' + date + '</p><p>' + snippet + '</p></div>'
$('#' + container_id).append(html)
}
}
})
}
function getEntries(rawXML){
var x2js = new X2JS();
console.log(rawXML);
var xml = rawXML.responseText;
match = xml.match(/<item>(.*)<\/item>/);
xml = match[0] || '';
var json = x2js.xml_str2json(xml);
json = json.rss.channel.item;
return json
}
</script>
<div id="rssfeed">
</div>
<div id="rss">
</div>
<script>
$(document).ready(function() {
buildRSS('rssfeed')
});
</script>
View Script
function AddToBag()
{
var url = "/Home/Populate_Entitle/";
$.ajax({
url: url,
data: { id: 1 },
cache: false,
type: "POST",
success: function (data) {
alert("hi");
$("#gridContent").html(markup);
},
error: function (reponse) {
alert("error : " + reponse);
}
});
}
Controller Functions
public ActionResult Populate_Entitle(int id)
{
if (dtEntitle.Columns.Count == 0)
{
dtEntitle.Columns.Add("sno");
dtEntitle.Columns.Add("Sport");
dtEntitle.Columns.Add("Event");
dtEntitle.Columns.Add("SubEvent");
dtEntitle.Columns.Add("Classification");
dtEntitle.Columns.Add("Entitlement");
dtEntitle.Columns.Add("Channel");
dtEntitle.Columns.Add("Brand");
dtEntitle.Columns.Add("product");
dtEntitle.Columns.Add("Unit");
dtEntitle.Columns.Add("TotalSpots");
dtEntitle.Columns.Add("TotalNetRevenue");
dtEntitle.Columns.Add("remark");
dtEntitle.Columns.Add("Sport_id");
dtEntitle.Columns.Add("Event_id");
dtEntitle.Columns.Add("SubEvent_id");
dtEntitle.Columns.Add("channel_id");
dtEntitle.Columns.Add("brand_id");
dtEntitle.Columns.Add("product_id");
dtEntitle.Columns.Add("Effective_Rate");
dtEntitle.Columns.Add("Base_Rate");
}
DataRow dr = dtEntitle.NewRow();
dr["sno"] = 1;
dr["Sport"] = "Cricket";
dr["Event"] = "IND vs BANGLADESH";
dr["SubEvent"] = "1st Day 18-JUN-2015,2nd Day 20-JUN-2015";
dr["Classification"] = "LIVE";
dr["Entitlement"] = "Spot Buys";
dr["Channel"] = "SS1,SS2";
dr["Brand"] = "Brand 1";
dr["product"] = "Product 1";
dr["Unit"] = "Spots";
dr["TotalSpots"] = 10;
dr["TotalNetRevenue"] = 200 ;
dr["remark"] = "-";
dr["Sport_id"] = 1;
dr["Event_id"] = 1;
dr["channel_id"] = 1;
dr["brand_id"] = 1;
dr["product_id"] = 1;
dr["Effective_Rate"] = 100;
dr["Base_Rate"] = 100;
dtEntitle.Rows.Add(dr);
List<Sports_Deal.Models.Entitlements> lmdEntitle = new List<Sports_Deal.Models.Entitlements>();
foreach (DataRow dr1 in dtEntitle.Rows) // loop for adding add from dataset to list<modeldata>
{
lmdEntitle.Add(new Sports_Deal.Models.Entitlements
{
Event = dr1["Event"].ToString(),
Base_Rate = Convert.ToInt32(dr1["Base_rate"]),
brand_id = Convert.ToInt32(dr1["brand_id"]),
Brand = dr1["brand"].ToString(),
Channel = dr1["Channel"].ToString(),
Sport = dr1["Sport"].ToString(),
Effective_Rate = Convert.ToInt32(dr1["Effective_Rate"]),
channel_id =(dr1["channel_id"]).ToString(),
Quality = (dr1["channel_id"]).ToString(),
Classification = dr1["Classification"].ToString(),
Entitlement = dr1["Entitlement"].ToString(),
Event_id = Convert.ToInt32(dr1["Event_id"]),
product_id = Convert.ToInt32(dr1["Product_id"]),
remark = dr1["remark"].ToString(),
sno = Convert.ToInt32(dr1["sno"]),
Sport_id = Convert.ToInt32(dr1["Sport_id"]),
SubEvent = dr1["SubEvent"].ToString(),
SubEvent_id = dr1["SubEvent_id"].ToString (),
TotalNetRevenue = Convert.ToInt32( dr1["TotalNetRevenue"]),
TotalSpots = Convert.ToInt32(dr1["TotalSpots"]),
Unit = dr1["Unit"].ToString()
});
}
return PartialView("markup", lmdEntitle);
}
}
I need to populate Web grid dybamically when controller method returns list.
Replace your markup with the Data
function AddToBag() {
var url = "/Home/Populate_Entitle/";
$.ajax({
url: url,
data: { id: 1 },
cache: false,
type: "POST",
success: function (data) {
alert("hi");
$("#gridContent").html(data);
},
error: function (reponse) {
alert("error : " + Json.stringify(reponse));
}
});
}
You are getting data in response, markup is undefined for this criteria
I have a code to put two cameras on my site:
$(document).ready(function(){
var m;
var index;
var IP;
var port;
var name;
var user;
var password;
var image_old;
var image_new;
var cameraFeed;
var topImage;
var urls = [];
$.ajax({
type: "GET",
url: "json.htm?type=cameras",
dataType: "JSON",
async : false,
success: function(data) {
for(m=0; m<=1; m++){
index = data.result[m].idx;
IP = data.result[m].Address;
port = data.result[m].Port;
name = data.result[m].Name;
user = data.result[m].Username;
password = data.result[m].Password;
image_old = data.result[m].ImageURL;
image_new = image_old.replace("#USERNAME", user).replace("#PASSWORD", password);
cameraFeed = "http://" + IP + ":" + port + "/" + image_new;
alert(cameraFeed + m);
urls.push(cameraFeed);
}
setInterval(function() {
var d = Date.now();
$.each(urls, function(i, url) {
$('#topImage' + i).attr('src', url + "×tamp=" + d);
});
}, 100);
},
error: function(data) {
alert("Error")
}
});
});
And html code:
<img id="topImage0" width="640px">
<img id="topImage1" width="640px">
I can not create a script to make setinterval work for both imgs. It works only for one of them. Any suggestions how to make it works ?
Set interval works only for one img.
To give you an idea how to structure your application code:
Get the data from the server
Create the URLs from data
Update each image every X milliseconds with those URLs
In code:
$.ajax({...}).done(function(data) { // get data from server
// create URLs
var urls = [];
for (var m = 0; m < 2; m++) { // why not iterate over data.results?
var cameraFeed;
// build cameraFeed ...
urls.push(cameraFeed);
}
// Update images
setInterval(function() {
var d = Date.now();
$.each(urls, function(i, url) {
$('#topImage' + i).attr('src', url + "×tamp=" + d);
});
}, 100);
});
Of course this can still be approved, but that should point you into the right direction. Note in particular that it is unnecessary to have a setInterval for each image. Just let a single interval update all images.
Especially the for loop can be approved upon. I don't know how many results data.results has and if you only want to get the first two, but this is an excellent use case for Array#map:
var urls = data.results.map(function(result) {
// ...
return cameraFeed;
});