I have problems to get data from Weather Underground from a historical day (same script works fine for my current observations). Example for yesterday:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
heute=new Date();
jahr=heute.getFullYear();
monat=heute.getMonth()+1;
tag = heute.getDate()-1;
jQuery(document).ready(function($) {
$.ajax({
url : "http://api.wunderground.com/api/ea1cb0c0f1995212/history_'+jahr+monat+tag+'/q/pws:INORDRHE156.json",
dataType : "jsonp",
success : function(parsed_json) {
var minhumidity = parsed_json.history.dailysummary[0].minhumidity;
var day = parsed_json.history.dailysummary[0].date.pretty;
document.getElementById("z8").innerHTML = minhumidity;
document.getElementById("z9").innerHTML = date;
}
});
});
</script>
So "day" works for me, output is: November 13, 2017
But "minhumidity" should bei '90' (or some other value), but there will be just a blank.
I get both values (day and minhumidity) at the same way, where is the Problem?
Sorry for my english.
your url "http://api.wunderground.com/api/ea1cb0c0f1995212/history_'+jahr+monat+tag+'/q/pws:INORDRHE156.json" change it to (note that i changed ' with "):
<script>
heute=new Date();
jahr=heute.getFullYear();
monat=heute.getMonth()+1;
tag = heute.getDate()-1;
jQuery(document).ready(function($) {
$.ajax({
url : "http://api.wunderground.com/api/ea1cb0c0f1995212/history_"+jahr+monat+tag+"/q/pws:INORDRHE156.json",
dataType : "jsonp",
success : function(parsed_json) {
var minhumidity = parsed_json.history.dailysummary[0].minhumidity;
var day = parsed_json.history.dailysummary[0].date.pretty;
document.getElementById("z8").innerHTML = minhumidity;
document.getElementById("z9").innerHTML = date;
}
});
});
</script>
And please add var, let, const whatever to your variables. For example:
var heute = new Date();
var jahr = heute.getFullYear();
var monat = heute.getMonth()+1;
var tag = heute.getDate()-1;
Related
I am creating a notification center, naturally it must be visible throughout the site; So the question is how do I do it.
Create a name.js file inside the static folder but it seems that something is missing since apart from the delay in the app itself it is not visible outside it.
view.py
#csrf_exempt
def NewsSubjects(request):
if request.is_ajax() == True:
queryset = Downloads.objects.all().order_by('register_date').values()[:5]
data=list(queryset)
return JsonResponse(data, safe=False)
urls.py
path('alerts/', views.NewsSubjects, name='alerts'),
/static/js/notifications.js
$.ajax({
// initialize an AJAX request
url: "alerts",
// al estar en static no se usa el name del URL ('control:alert') sino el PATH (alerts/)
type: "GET",
datatype:'json',
success: function(data) {
console.log('cambio')
var opciones = document.getElementById("nuevasDisciplinas");
var countAlert = document.getElementById("countAlert");
var listaDisciplinas = ''
for (var i = 0; i < data.length; i++) {
// console.log(data[i]);
var nombDis = data[i].category_name
var fechaCreacion = data[i].register_date
// var d = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(fechaCreacion)
// var m = new Intl.DateTimeFormat('en', { month: 'short' }).format(fechaCreacion)
// var a = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(fechaCreacion)
var icon = '<divclass="mr-3"><divclass="icon-circle bg-primary"><iclass="fas fa-file-alt text-white"></i></div></div>'
var body ='<div><divclass="small text-gray-500">'+fechaCreacion+'</div><spanclass="font-weight-bold">'+nombDis+'</span></div>'
listaDisciplinas += icon+body
}
opciones.innerHTML = listaDisciplinas;
countAlert.innerHTML = data.length;
},
error: function() {
console.log("The information could not be obtained");
}
});
master.html
<script src="{% static 'js/notifications.js' %}"></script>
the idea is simple, bring the latest records according to the date of registration (the best option would be the login date to the system but good), this works in the notification app but not in the rest.
It returns the message that I put in case of error.
PS: if you can lend me a hand with the formatting of the date it would be fine too
you have to use the path of the url instead of the name, that is, the name of the app/url/
Django the urls.py they consist of path(this_url, view, name_url) so to use it throughout the Django site you must use app/this_url/
in my case
my urls.py
path('alerts/', views.NewsSubjects, name='alerts'),
in the ajax url it would be
$.ajax({
url: "app_name/alerts/",
...
});
I have an epub3 book with 2 pages as well as a Table of Contents Page. I am viewing this book in Apple's Books, their inbuilt epub3 reader, on Mac OSX. The two pages appear side by side. The first page is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=500, height=600"/>
</head>
<body>
<p id="result"></p>
<script>
//<![CDATA[
var current_page = "1";
var other_page = "2";
var t = 0;
setInterval(function() {
var d = new Date();
var storage = localStorage;
storage.setItem("t"+ current_page, d.toLocaleString());
document.getElementById("result").innerHTML = storage.getItem("t"+ current_page) +" "+storage.getItem("t"+ other_page);
}, 1000);
//]]>
</script>
</body>
</html>
and the only thing different in my second page is:
var current_page = "2";
var other_page = "1";
So every second, Page 1 saves the current time to Local Storage as t1, and Page 2 does the same for the value t2. At the same time, both pages are reading both t1 and t2 from Local Storage, before their values are displayed to screen. However in ibooks, Page 1 only manages to display the current value for t2 when the page is reloaded - like when I flip to the Table of Contents and then back to Page 1 and 2 again. With something similar happening for Page 2 with regard to t1.
So at time 21:10:00, Page 1 might display:
08/09/19, 21:09:18 08/09/19, 21:08:58
and Page 2:
08/09/19, 21:09:22 08/09/19, 21:08:01
I also tried using Session Data but Page 1 can't ever read t2 and Page 2 can't read t1. So, this would be displayed instead:
08/09/19, 21:09:18 null
I can think of several applications where it would be very useful for Pages to communicate with each other.
For example, if a video is playing on one page, it would be useful to stop it if a video on another page is started. This would normally be done using Session Storage. This is related to my own use case and the reason I started exploring this problem.
Likewise, if the user is asked on Page 1 to enters the name of the main character of the story, then that entry should appear immediately on Page 2 once it is entered.
Is there any other way for Pages to communicate with each other in epub3 other than Local or Session Storage?
I dont know epub3 and dont have a MAC to test, but here are four possible solutions that come to my mind:
Cookies
It is not as performant as localStorage for that use-case, but if you dont have many options, better that than nothing.
Functions to create, read and delete cookies (Credits to https://stackoverflow.com/a/28230846/9150652):
function setCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
document.cookie = name+'=; Max-Age=-99999999;';
}
Usage for your example:
<script>
//<![CDATA[
var current_page = "1";
var other_page = "2";
var t = 0;
setInterval(function() {
var d = new Date();
setCookie("t"+ current_page, d.toLocaleString(), 100); // 100 days
document.getElementById("result").innerHTML = getCookie("t"+ current_page) +" "+getCookie("t"+ other_page);
}, 1000);
//]]>
</script>
BroadcastChannel
BroadcastChannel is a very new functionality, so it might not be supported by the "Books" app. But here is a concept:
<script>
//<![CDATA[
var broadcaster = new BroadcastChannel('test');
var current_page = "1";
var other_page = "2";
var t = 0;
setInterval(function() {
var d = new Date();
// Send message to all other tabs with BroadcastChannel('test')
bc.postMessage({
senderPage: "t"+ current_page,
date: d.toLocaleString()
});
}, 1000);
broadcaster.onmessage = (result) => {
if(result.senderPage == "t"+ other_page) { // If the message is from the other page
// Set HTML to current date + sent Date from other page
var d = new Date();
document.getElementById("result").innerHTML = d.toLocaleString() +" "+result.date;
}
};
//]]>
</script>
Some sort of Backend
If none of the above works, you probably have no other option, than to use some sort of backend, to provide and save the data
If it is just for you, I suggest you to use a free tier of Firebase or MongoDB Atlas, as they both provide quite some value on their free tier.
If you do it with a Backend, it could be done with something like this:
<script>
//<![CDATA[
var current_page = "1";
var other_page = "2";
var lastLocalDate = new Date();
const serverUrl = "http://someUrl.com/endpoint/"
// Gets the latest date of the other page via ajax
function getUpdate() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
// If successful, update HTML
if (xmlhttp.status == 200) {
document.getElementById("result").innerHTML = lastLocalDate.toLocaleString() +" "+xhr.responseText;
}
// Update the date of this page anyways
sendUpdate();
}
};
// GET request with parameter requestingPage, which is the other page
xmlhttp.open("GET", serverUrl, true);
xmlhttp.send(`requestingPage=${other_page}`);
}
// Sends the current date of this page to the webserver
function sendUpdate() {
var xmlhttp = new XMLHttpRequest();
// No need to check if successful, just update the page again
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
getUpdate();
}
};
lastLocalDate = new Date();
// POST request with parameters page and date
xmlhttp.open("POST", serverUrl, true);
xmlhttp.send(`sendingPage=${current_page}&data=${lastLocalDate.toLocaleString()}`);
}
// Start with sending an update (so that lastLocalDate is at least sent once to the server)
sendUpdate();
//]]>
</script>
And some methods in your backend that need to look something like this (note that this is not valid code in any language):
#GET
function getDate(requestingPageId)
find latest entry with page.id == requestingPageId
return page.date
#POST
function saveDate(savingPage, savingDate)
store new page element with
page.id = savingPage
page.date = savingDate
And a collection in your database looking like this:
[
{
id: 1,
date: "date"
},{
id: 2,
date: "date"
},{
id: 2,
date: "date"
},{
id: 1,
date: "date"
},
// ...
]
Window References
If the Books app opens the second tab from the first tab, it might be worth to look into:
Window.postMessage()
With its functions:
Window.open()
to open the second tab and get a reference to it
And Window.opener to get a reference to the opener
I need to call a controller from javascript. I've already success to call the controller, but if the controller has no paramater.
In my cases, the controller has a parameter. How can i can call the controller from javascript
Javascript code:
<script language="javascript" type="text/javascript">
var thisTable = setFilterGrid("myTable");
document.getElementById("oneday").onclick = function() {
var date = new Date();
var day = date.getDate().toString();
var month = date.getMonth().toString();
var year = date.getFullYear().toString();
var oneday = day.concat('/', month, '/', year);
window.location.href = "<?php echo site_url('sellbyitem/retrieveInfo('/*howcanipassonedayhere*/');?>";
};
Controller:
public function retrieveInfo($date) {
echo $date;
}
I've already looking for same cases, but it doesn't work for me
You can pass javascript parameter at end like following :
window.location.href = "<?php echo site_url('sellbyitem/retrieveInfo/');?>" + oneday ;
I have a select box which after change fire a script (and made a change of date in input text field):
$(window).load(function() {
datum = function() {
var platba = document.getElementById('payment').value;
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
today = dd + '.' + mm + '.' + yyyy;
if (payment = 'yes') { datet = today; }
document.getElementById('datepayment').value = datet;
It works great, but now I need to call a jQuery function which save the new value into dtb...
This is made by following script (which works automatically after change in input fields in whole form):
<!--JQUERY-->
<script type='text/javascript'>
// JQUERY: Plugin 'autoSumbit'
(function($) {
$.fn.autoSubmit = function(options) {
return $.each(this, function() {
// VARIABLES: Input-specific
var input = $(this);
var column = input.attr('name');
// VARIABLES: Form-specific
var form = input.parents('form');
var method = form.attr('method');
var action = form.attr('action');
// VARIABLES: Where to update in database
var where_val = form.find('#where').val();
var where_col = form.find('#where').attr('name');
// ONBLUR: Dynamic value send through Ajax
input.bind('blur', function(event) {
// Get latest value
var value = input.val();
// AJAX: Send values
$.ajax({
url: action,
type: method,
data: {
val: value,
col: column,
w_col: where_col,
w_val: where_val
},
cache: false,
timeout: 10000,
success: function(data) {
// Alert if update failed
if (data) {
alert(data);
}
// Load output into a P
else {
$('#notice').text('Updated');
$('#notice').fadeOut().fadeIn();
}
}
});
// Prevent normal submission of form
return false;
})
//
});
}
})(jQuery);
// JQUERY: Run .autoSubmit() on all INPUT fields within form
$(function(){
$('#ajax-form INPUT').autoSubmit();
$('#ajax-form SELECT').autoSubmit();
$('#ajax-form TEXTAREA').autoSubmit();
});
</script>
Question is: how to save the value in field datepayment into database without click into it? Thank you for comments!
Instead of
input.bind('blur', function(event)
Try
input.on('input', function() {
Here is a simple example:
<input type="text" id="input1"/>
<input type="text" id="input2"/>
<select id="input3">
<option value="ABC">ABC</option>
<option value="XYZ">XYZ</option>
</select>
$(document).ready(function() {
$("#input1").on('input', function() { //'input' listener
alert($("#input1").val());
});
$("#input2").on('input', function() { //'input' listener
alert($("#input2").val());
});
$("#input3").on('change', function() { //'change' listener
alert($("#input3").val());
});
});
jsfiddle link: https://jsfiddle.net/kannanore/xdat6axa/
Below is my code
<script type="text/javascript">
var Tag1, Tag2, Tag3, Tag4;
var Data1,Data2,Data3,Data4;
function onDeviceReady() {
$.ajax({
type : 'GET',
url : "http://192.168.1.150:9051/something.xml",
data : {
key : "value"
},
dataType : "xml",
success : function(xml) {
Tag1 = $(xml).find('Tag').eq(0).text();
Tag2 = $(xml).find('Tag').eq(1).text();
Tag3 = $(xml).find('Tag').eq(2).text();
Tag4 = $(xml).find('Tag').eq(3).text();
Data1 = $(xml).find('Data').eq(0).text();
Data2 = $(xml).find('Data').eq(1).text();
Data3 = $(xml).find('Data').eq(2).text();
Data4 = $(xml).find('Data').eq(3).text();
var oHead1 = document.getElementsByTagName('HEAD').item(0);
var paramScript = document.createElement("script");
paramScript.type = "text/javascript";
paramScript.setAttribute('Tag1', Tag1);
paramScript.setAttribute('Tag2', Tag2);
paramScript.setAttribute('Tag3', Tag3);
paramScript.setAttribute('Tag4', Tag4);
paramScript.setAttribute('Data1', Data1);
paramScript.setAttribute('Data2', Data2);
paramScript.setAttribute('Data3', Data3);
paramScript.setAttribute('Data4', Data4);
oHead1.appendChild(paramScript);
var oHead = document.getElementsByTagName('HEAD').item(0);
var oScript = document.createElement("script");
oScript.type = "text/javascript";
oScript.src = "something.js";
oHead.appendChild(oScript);
},
error : function(xhr) {
alert("Error while loading the Mock Service !!!");
}
});
}
document.addEventListener("deviceready", onDeviceReady, false);
</script>
Now suppose if this is called in one.html and it displays the values correctly.But suppose if i go to second.html and then i manually change the server values in something.xml and then if i return back to one.html then the values doesnt get changed.It shows the old values. The changes is not affected. What am i doing wrong?
It maybe due to some cache issue. You could try something like:
url : "http://192.168.1.150:9051/something.xml" + "?time=" + Date.now(),
to try avoid it.