Angularjs' $http.get only executed once in IE11 - javascript

I'm learning angularjs, and as a test project I'm polling a server that returns a list of active processes (their pids) and displaying these.
The client code looks like this:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="static/angular/angular.js"></script>
<script>
function ProcessCtrl($scope, $http, $interval) {
$scope.ReloadData = function() {
var result = $http.get("processdata", {timeout:1000});
result.success(function(data,status,headers,config) {
$scope.processes = data;
});
}
$scope.ReloadData();
var stop = $interval(function(){$scope.ReloadData()}, 1000);
}
</script>
</head>
<body ng-app>
<div ng-controller="ProcessCtrl">
Processes:
<ul>
<li ng-repeat="process in processes">
{{process.pid}} is running
</li>
</ul>
</div>
</body>
</html>
This works in Firefox and Chrome, but not quite in Internet Explorer 11.
All browsers execute the ReloadData method every second, but IE11 doesn't actually fetch the process data from the server. Firefox and Chrome do fetch the data every second. I can see this also in the output from my server, which logs every request.
All three browsers execute the code in result.success, but IE11 keeps reusing the old data it got the first time, where FireFox and Chrome use the newly fetched data.
I've checked the web console in IE11 for warnings or errors, but there are none.
Edit:
As the chosen answer suggested it was a caching problem. I have made the server add a 'cache-control' header to the response with the value 'no-cache'. This has solved the problem.

It's possible that the request is cached, as it is valid to cache GET requests. FF and Chrome probably have disabled caches, because of running dev tools or other reasons. You could append a timestamp as url query string "processdata?" + (new Date()).getTime() to see if it is a caching problem.
Prettier ways to prevent IE caching can be found here:
Angular IE Caching issue for $http

I prefer to use $http.post in order to prevent any cache.

Related

Cookies not working when page accessed via file://

My code works in firefox and when i visit w3schools using chrome to test my code in their editor it works fine too but when i launch my code in chrome from notepad++ it doesn't work.It seems that body onload is not working because i don't get the alert.My chrome is up to date.Help would be appreciated.
<!DOCTYPE html>
<html>
<head>
<script>
function setCookie(cname,cvalue,exdays){
var d=new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires="expires="+d.toUTCString();
document.cookie=cname +"="+cvalue+"; "+expires;
}
function f(){
var user=prompt("What is your name?","");
if(user!="" && user!=null){
setCookie("username",user,30);}
}
function getC(cname){
var name=cname+"=";
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);
if(c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
function checkcooki(){
var user=getC("username");
if(user!=""){
alert("Welcome back "+user);
}
}
</script>
</head>
<body onLoad="checkcooki()">
<input type="button" onclick="f()" value="klick">
</body>
</html>
For a fact: Using the file:// protocol does NOT guarantee the proper workings with cookies. Since cookies need 3 things:
A name-value pair containing the actual data
An expiry date after which it is no longer valid
The domain and path of the server it should be sent to
The domain tells the browser to which domain the cookie should be sent. If you don't specify it, it becomes the domain of the page that sets the cookie.
On a file:// protocol you don't have a domain.
Now some browsers might have found work-arounds for this, like FireFox and IE. You can test your code on these browsers but they will not use cookies in the same way as on a webserver.
Proper x-browser testing in your case requires the http:// protocol.
I suggest you start a jsfiddle or setup a webserver(IIS, apache).
Proper read on cookies: quircksmode
If you are still persistent to get it working on chrome through the file:// protocol you might have a small chance if you get the path correctly.
path: properly escaped path => encodeURIComponent(document.domain) or "c:\/my%20folder\/index.html" (along these lines but again, very untrustworthy information here)
domain: "/" (no idea what else you can try here)
Your user variable must be a blank string.
Put an alert at the very top of your checkcooki() function to verify that body onload works.

jQuery ajax get response not parsed or not seen

The problem is that jQuery does not receive the response by the server, and I can't figure out why. This is my setup, Windows 7 64bit:
ext.js:
$('#button').click(function(){
var string= $('#string').val();
$.get('http://localhost:3000',
{"input":string},
function(data){
alert(data);
$('#feedback').text(data);
});
})
099.html:
<doctype html>
<html lang="en">
<head> <!-- charset title style -->
<meta charset="uft-8"/>
<title>jQuery 099</title>
</head>
<body><!-- tables, div's bad, html 5 is better: -->
<input type="text" id="string" value=""/>
<input type="button" id="button" value="ajax"/>
<br/>
<div id="feedback"></div>
</body>
<script type="text/javascript" src="./js/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="./js/ext.js"></script>
</html>
server.js:
var express = require('express');
var app = express();
app.get('/', function(req, res){
console.log("got");
console.log(req.query.input);
var content = req.query.input;
res.send(content);
});
app.listen(3000);
I run node 0.10 from command line using
C:\dev\nodejs\0.10\servers\stackoverflow>node server.js
In my FF browser i type
http://localhost:3000/?input=hi
and i get a blank screen containing hi,
which is good. Also node.js prints got and then hi on the command line
I run 099.html from notepad++ > run > chrome > so it runs on a completely other drive but surely it doesn't need to be in a server, right? When i type something XYZ the textfield and click ajax button, node responds on the console XYZ, which is good: the request is discovered by node, so it would send a response, but i don't see the response in my html.
The expected behavior was an alert and my div gets filled in the html and displays XYZ.
What obvious point am i missing?
I'm stuck for 2 hours now and couldnt find a similar question perhaps because of my not knowing jquery.
ps the 099 is from the newboston youtube tutorial and jquery is from the jquery site. i don't know the express version, it's a fairly new one.
ps2: the jquery $.get() api is too vague:http://api.jquery.com/jquery.get/ states: "A callback function that is executed if the request succeeds." well, can i conclude that the request succeeded because the nodejs console reacted to it, and if so, why did the callback function not execute.
ps3: the last argument is dataType, perhaps node responds in a way $.get did not expect? any datatype suggestions?
EDIT: yesterday i dusted off my tomcat and put the above files into it and jquery runs like a charm.
How stupid of me, assuming that a file on a disk can communicate over http to a server, what was i thinking.
the essence of ajax is "listening for the asynchronous response" (for example http://msdn.microsoft.com/en-us/magazine/cc163479.aspx), so the file needs to reside in something that establishes an IP address of some kind obviously. Sorry for polluting the Internet, case closed.
You cannot alter port number when issuing ajax request - this is Same origin policy restriction. See what you can do with SocketIO instead.

Issue using jQuery to do a google maps api call (JSON not being returned)

This is the code I was originally using and worked perfectly fine up until yesterday (which is when I noticed it but I am unsure when it actually stopped working for sure). I know this was working at the beginning of last week so sometime between then and yesterday it broke. I am running this code within a RAD called Alpha Anywhere but have tested it outside of this program (in just a HTML page) and it still didn't work. Hoping someone knows if there is a bug or if there is something I can do to fix this issue. I ran this in firefox with firebug on and that is where I saw the error letting me know that the JSON wasn't retrieved.
var $jq = jQuery.noConflict();
$jq.getJSON('http://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&sensor=false',function(results){
// I have code in here to calculate miles driven per state
// (as in the above code origin and destination would be filled
// with variables but I went with this basic call because even this doesn't work).
});
This following code does not work (as of right now November 11, 2013 at 10:26 PM CDT) when running it in firefox or chrome. With firebug on it shows I am not getting a response from google. However this following code does respond when ran in safari 7.0.x on Mac OSX 10.9.
<!DOCTYPE html>
<html>
<head>
<script src="http://api.jquery.com/jquery-wp-content/themes/jquery/js/jquery-1.9.1.min.js"></script>
<script>
function getData() {
var url = 'http://maps.googleapis.com/maps/api/directions/json?origin=Huntsville,AL&destination=Atalanta,GA&sensor=false';
var $jq = jQuery.noConflict();
$jq.getJSON(url, function (results) {
alert(results.routes[0].legs[0].distance.value);
});
}
</script>
<title>jQuery Debug of Google API</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<button onclick="getData();">click</button>
</body>
</html>
There are a couple problems here:
First, from jsonp explained:
As you may be aware you cannot directly load data files from another domain. This is a security issue that has been around for a long time and is commonly solved by sharing data through an API, REST or such. However there are ways around this ... [for example] JSONP
To do this in jQuery:
Using $.ajax, add dataType: 'jsonp', which appends callback=? to the URL
Using $.getJSON (shorthand for .ajax), add callback=? at the end of the requested URL.
That indicates that we want to use JSONP. Remove it and a vanilla JSON request will be used; which will fail due to the same origin policy.
Another issue is that some external APIs (like Google Maps Directions API), don't automatically serve JSONP. If the server doesn't know what to do with the callback parameter then the response from the API will still be JSON, not JSONP. In order to ensure the returned content is formatted correctly, you can go through a proxy server like the jsonp.guffa.com
To use it, change the request to http://jsonp.guffa.com/Proxy.ashx?url=YourEncodedURI
Where you have replaced YourEncodedURI with the encoded requested url string.
Putting it all together:
var mapsUrl = 'http://maps.googleapis.com/maps/api/directions/json' +
'?origin=Toronto&destination=Montreal&sensor=false';
var encodedUrl = encodeURIComponent(mapsUrl);
var proxyUrl = 'http://jsonp.guffa.com/Proxy.ashx?url=' + encodedUrl;
$.ajax({
url: proxyUrl,
dataType: 'jsonp',
cache: false,
success: function (data) {
console.log(data);
}
});
Working Demo in jsFiddle
Further Reading:
What is JSONP all about?

How to use web sockets

I'm trying to make use of Easy Websockets to come up with a chat application.
http://easywebsocket.org/
Here's the code I have right now. As you can see, I'm trying to log the message on the console every time I click on the send button. It works when I open it up on 2 browsers. But it only works for less than 1 minute.
<input type="text" id="txt"/>
<input type="button" value="send" id="sends"/>
<div id="messages"></div>
<script src="jquery171.js"></script>
<script src="easywebsockets.js"></script>
<script>
var socket = new EasyWebSocket("ws://sample.com/resource");//I do not understand this part
socket.onopen = function(){
socket.send("hello world.")
}
socket.onmessage= function(event){
console.log(event.data)
}
$('#sends').click(function(){
var txt = $('#txt').val()
socket.send(txt)
});
</script>
I got this error log from firebug:
I don't really understand what this all means. Is there something I need to setup in order to make this work?
It usually happens when the client doesn't use the same protocol version as the server. The server should specify what version it uses, socket.io by default goes with RFC6455 but it can be overridden to go with older hybi-0x.
So, check the following:
client & server implemented protocol versions
origin (e.g. localhost) is permitted by server
firewalls, internet security suites, zonealarms, that kind of stuff

Continuous page refresh causes Firefox to increase memory consumption on windows

I have an odd situation with a webapp that keeps running down memory on Firefox / Windows. Basically the app refreshes the data in the page using a POST call to the server made via jQuery. Every time the call is made, Firefox's memory consumption increases in an amount that's disproportional to the size of the data returned from the server.
To see if this was specific to my app, I wrote a simple test app using Sinatra (Ruby 1.9.2-p318) and jQuery (1.7.1). The app sends a request to the server every 10 seconds and loads a 1MB html chunk to the page:
Server side:
require 'rubygems'
require 'sinatra'
require 'erb'
require 'json'
configure do
set :static, true
end
post '/' do
content_type :json
# a simple html file containing ~ 1MB of data
html = File.read( File.join(File.dirname(__FILE__), 'html.txt' ) )
# convert to JSON and return to the client
return { "html" => html }.to_json
end
Client side:
<!doctype html>
<html>
<head>
<script type="text/javascript" src="/js/jquery-1.7.1.min.js"></script>
</head>
<body>
<h1>Test Page</h1>
<div id="results" style="display: none;"></div>
<script type="text/javascript">
$(function(){
// refresh the data every 10 sec
setInterval( function(){ doRefresh(); }, 10 * 1000 );
});
function doRefresh() {
$.post('/', function(data){
$('#results').html( data.html );
// attempt to free some memory
delete data;
}, 'json');
}
</script>
</body>
</html>
What doesn't seem to change is that the memory consumption by the Firefox process (observed through Windows' Task Manager) keeps rising in 10's of megabytes with each call. Despite the fact that the new data replaces the old one in the page, it seems Firefox isn't disposing of that allocated space in memory. Turns out this runs down the memory completely if the page is left open overnight (on simple, 4GB machines).
Is this a javascript issue or something with Firefox? Can I somehow force garbage collection in either? thanks.
EDIT: This memory issue wasn't observed with Google Chrome (13.0.782.112 on Win7).
If your 'data' argument has been instantiated with the 'new' keyword by jQuery, you should write this code :
…
$('#results').html( data.html );
delete data;
…
If deleting the data variable returns false. I think you can't do anything.

Categories

Resources