I'm limiting the amount of certain pop up windows with a static counter in the back-end of my web form application (C#). I only want to have 1 window open at a time. The back-end counter works fine, however when a user closes the child window I want to reset the counter in the back-end. For that I'm using AJAX with JS (can't use JQuery) and I'm calling that AJAX to make a POST in the back-end in an onUnload event.
I'm using IE 11.
Back-end method I want to call from my JavaScript.
public void DecreaseItem1()
{
int? inspID = convert.ToInt(Request.QueryString["inspid"]);
int? inpID_static = InspectionList.GetWindowInspID();
string path = HttpContext.Current.Request.Url.AbsolutePath;
if (path.Contains("ReadOnlyInspection"))
{
if (inspID != inpID_static)
{
InspectionList.DecreaseCounter();
}
else
{
InspectionList.DecreaseCounter();
InspectionList.SetGetWindowInspID(null);
}
}
From my front-end I'm calling onUnload the DecreaseItem() JavaScript function.
Body tag
<body onUnload="DecreaseItem()" >
JavaScript function:
<script type="text/javascript">
function DecreaseItem() {
var win_loc = "ReadOnlyInspection.aspx/DecreaseItem1";
var xhttp = new XMLHttpRequest();
xhttp.open("POST", win_loc, true);
xhttp.send();
}
</script>
[problem] Counter never gets decreased. Any help or suggestion is greatly appreciated.
Related
using vanilla JS, i need to know if someone is using my chrome extension on a private webpage or a public webpage.
example of public webpage
https://ww.facebook.com/home
example of private webpage
https://ww.facebook.com/account/settings
Are you able to figure out if a webpage is accessible by everyone or login permissions
what i have
let xhr= new XMLHttpRequest();
xhr.open('GET', 'www.facebok.com/account/settings');
xhr.responseType = 'json';
xhr.onload = function() {
let res = xhr.state;
//res == 503?
};
xhr.send();
However, i think that since my app runs on their browser, their session will be saved and it will return a false positive.
There is no standard way of checking that for "normal" websites.
Some might in fact return a proper status code, but others (like Facebook) won't and will instead render the same 200 (OK) status page for every URL and handle the login/redirects internally via JavaScript. (This is oversimplified for the sake of this example)
You will have to write separate detection algorithms for every page you want to check.
I am trying to reload a page every 10 seconds , using Cache Scheduler method mentioned here,
I just want call a JavaScript function to reload current page when Cache is removed. But for some reason basic JavaScript doesn't work.
Razor View:
#{
AddTask("CheckStatus", 10); // reload page every 10 seconds
#functions
{
private static System.Web.Caching.CacheItemRemovedCallback OnCacheRemove = null;
public void AddTask(string name, int seconds)
{
OnCacheRemove = new System.Web.Caching.CacheItemRemovedCallback(CacheItemRemoved);
HttpRuntime.Cache.Insert(name, seconds, null,
DateTime.Now.AddSeconds(seconds), System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.NotRemovable, OnCacheRemove);
}
public void CacheItemRemoved(string k, object v,
System.Web.Caching.CacheItemRemovedReason r)
{
PrintStatus();
}
}
}
#helper PrintStatus()
{
var msg = "<script language='javascript' type='text/javascript'>
alert('Status is open!');</script>";
#Html.Raw(msg)
}
What am i doing wrong ? Or Is there any alternate way to return Javascript to reload page using server side code.
Note: I am not using Javascript set interval because Chrome has issues when the browser is minimized, so i prefer server side code to reload page every x seconds.
Any help would be great.
The cache scheduler is server-side piece of code. It is useless on client. The way this would fire is only if by some miracle the CacheRemoveItem will fire when you're rendering the view.
If I were you I'd create some AJAX service and periodically call it from javascript using setInterval.
What I'm looking for is this.
I have a simple PHP page with a submit button that is disabled by default.
I want the submit button to be enabled at a particular time for example 02:00:00
With PHP i can get the time from server with date("h:i:s") which i am using in a JS variable.
like
var time = "<? php echo date("h:i:s") ; ?>" ;
Now by using setInterval() method every millisec i am trying to compare the value of "time" variable with the
particular time i want the button to be enabled.
like if(time=="02:00:00")
{
button.disabled=false;
}
But the problem is "time" variable should also dynamically change to meet the conditions otherwise nothing will happen.I can't get any simple solution.Do i require AJAX for this?
Any help will be appreciated :)
Thanx!
I would update the time variable using JavaScript:
var curTime = new Date();
var firstColon = curTime.toString().indexOf(":");
time = curTime.toString().substring(firstColon-2, firstColon+6)
I'm a Python person, but I think PHP servers work similarly in that when going to a link, a GET request is sent, and then data is sent back, possibly a dynamically created webpage with Python code, but that webpage can't contain any Python or PHP. Those languages are strictly server-side. You could send a request to the server to get the time, but that would be really inefficient and it's better to do this client side then constantly dynamically change the webpage with requests to your PHP server.
Since this is about disabling a button, if the button sends a request to the server, remember to check that the time is right server-side just in case someone tampered with the webpage using their JavaScript console client-side.
Isn't this enable/disable done better at server side? Why do you need to enable the submit button in JavaScript at all? Will it be too bad of a solution to simply inform the user that they cannot submit operation is not available at the moment? They can always refresh the page or come back later to see if it is enabled.
Alternatively, you can simply have an ajax request that periodically pings the server to see if the button can be enabled or not. But know that a savvy user can use Web Inspector tools available in modern browsers to change DOM state. Always validate your operations at the server side. Hope this helps.
Try the following
/* ########## HTML file ######### */
<html>
<head>
</head>
<body onload="timer_function();">
<button type="submit" id="validateIt" style="none">Submit</button>
</body>
<script type="text/javascript">
function AjaxFunction()
{
var httpxml;
try
{
// Firefox, Opera 8.0+, Safari
httpxml=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
httpxml=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
httpxml=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateck()
{
if(httpxml.readyState==4)
{
//document.getElementById("msg").innerHTML=httpxml.responseText;
//document.getElementById("msg").style.background='#f1f1f1';
}
if(httpxml.responseText == "02:00:00")
{
document.getElementById('validateIt').style.display = 'block';
}
if(httpxml.responseText >= "00:00:00" && httpxml.responseText < "02:00:00"
|| httpxml.responseText >= "02:05:00" && httpxml.responseText < "02:00:00")
{
document.getElementById('validateIt').style.display = 'none';
}
}
var url="server-clock-ckk.php";
url=url+"?sid="+Math.random();
httpxml.onreadystatechange=stateck;
httpxml.open("GET",url,true);
httpxml.send(null);
tt=timer_function();
}
function timer_function(){
var refresh=1000; // Refresh rate in milli seconds
mytime=setTimeout('AjaxFunction();',refresh)
} // Display server time ends
</script>
</html>
/* ########## PHP file server-clock-ckk.php ######### */
<?Php
echo date("H:i:s", time());
?>
I am trying to get text from a service on the same server as my webserver. The link is something like this:
http://<OwnIPadres>:8080/calc/something?var=that
This is my code:
function httpGet(theUrl)
{
alert(theUrl);
var doc = new XMLHttpRequest();
doc.onreadystatechange = function() {
if (doc.readyState == XMLHttpRequest.DONE) {
alert("text: " + doc.responseText );
document.getElementById('ctm').text = doc.responseText;
}
}
doc.open("get", theUrl);
doc.setRequestHeader("Content-Encoding", "UTF-8");
doc.send();
}
The url that i print in my first alert is the good one if i test in my browser, it is an html page with a table in it. But the alert of my text is empty? Is it a problem that the text is html?
Actually, its quite ok that your 'text' is 'html'. The problem is that using a different port counts as cross-site scripting. Therefore, your XMLHttpRequest is being stopped by the browser before it actually reaches your page across port 8080.
I'm not sure what else you're doing before and around this code snippet, but you could try an iframe call to your url to get your data, or you could add an
Access-Control-Allow-Origin: http://:8080/
in your header (however that will only get you the most modern browsers).
Finally, you could pull in a JS framework like JQuery which could help you with pulling in this service data.
I'm currently programming in JSP and Javascript. (I am by no means an expert in either). Right now, what I want is for a Javascript function to be called repeatedly and one of the variables to be queried from the database repeatedly (it is the date that the page was last modified). If this variable is greater than when the page was loaded, I want the page to refresh.
What I have so far:
...
<body onload="Javascript:refreshMethod()">
<script type="text/JavaScript">
<!--
function refreshMethod()
{
var interval = setInterval("timedRefresh()", 10000);
}
function timedRefresh() {
var currenttime = '<%=currentTime%>';
var feedlastmodified = '<%=EventManager.getFeedLastModified(eventID)%>';
var currenttimeint = parseInt(currenttime);
var feedlastmodifiedint = parseInt(feedlastmodified);
if(feedlastmodifiedint > currenttimeint)
{
alert(feedlastmodifiedint);
setTimeout("location.reload(true);",timeoutPeriod);
}
if(feedlastmodifiedint < currenttimeint)
{
alert(feedlastmodifiedint + " : " + currenttimeint);
}
}
// -->
</script>
The problem is that everytime the timedRefresh runs, the feedlastModifiedInt never changes (even if it has been changed).
Any help would be appreciated,
Thanks.
The JSP code within the <% ... %> tags runs only once, on the server-side, when the page is loaded. If you look at the source of the page in the browser, you will find that these values have already been placed within the JavaScript code, and thus they will not change during each timer interval.
To update the data as you are expecting, you can use AJAX. You can find plenty of tutorials online.
JSP and JavaScript doesn't run in sync as you seem to expect from the coding. JSP runs at webserver, produces a bunch of characters which should continue as HTML/CSS/JS and the webserver sends it as a HTTP response to the webbrowser as response to a HTTP request initiated by the webbrowser. Finally HTML/CSS/JS runs at the webbrowser.
If you rightclick the page in webbrowser and choose View Source, you'll probably understand what I mean. There's no single line of Java/JSP code. It has already done its job of generating the HTML/CSS/JS. The only communication way between Java/JSP and JavaScript is HTTP.
You need to move this job to some servlet in the server side and let JS invoke this asynchronously ("in the background"). This is also known as "Ajax". Here's a kickoff example with a little help of jQuery.
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
var refreshInterval = setInterval(function() {
$.getJSON('refreshServlet', function(refresh) {
if (refresh) {
clearInterval(refreshInterval);
location.reload(true);
}
});
}, 10000);
});
</script>
Where the doGet() method of the servlet which is mapped on an url-pattern of /refreshServlet roughly look like this:
response.setContentType("application/json");
if (EventManager.getFeedLastModified(eventID) > currentTime) {
response.getWriter().write("true");
} else {
response.getWriter().write("false");
}
See also:
Communication between Java/JSP/JSF and JavaScript