get requests fail when cache manifest is applied - ajax

I'm comfortable working with $.ajax and also in using cache.manifest. Recently I decided to start using "get" instead of "post" to help see the parameters easier.
In this proof-of-concept, if I delete the cache.manifest from the server, everything works. But when I put the cache.manifest on the server, the page stops working with an undefined jqXHR.responseText.
Furthermore, if I change the get to a post, it works with the cache.manifest.
Q: Does an https require a post, making "get" invalid if you are using a cache manifest? It seems to be working if the cache manifest is missing and it works with the cache manifest if I use post.
var local = {}
local.type = 'get'
local.dataType = 'text'
local.data = {}
local.data.CtrlName = 'testing123'
var promise = $.ajax('where_ctrlName.cfm',local)
promise.done(done)
promise.fail(fail)
function done(response) {
console.log(response)
}
function fail(jqXHR, textStatus, errorThrown) {
debugger
}
window.applicationCache.addEventListener('updateready', updateReady, false)
function updateReady() {
if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
$('body').html('<h1>Updating</h1>')
setTimeout(reloadCache,1000)
}
}
function reloadCache() {
window.location.reload()
}
<html manifest="cache.manifest">
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
</html>
Here's my cache.manifest:
CACHE MANIFEST
https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js
For What It's Worth, this is an https call.

Related

Getting 500 ERROR when doing an AJAX request in Laravel

I'm new to Laravel. I'm trying to make an AJAX request in my laravel app but I'm getting a 500 (Internal Server Error).
So, here is my request in the .blade file:
<script>
$(document).ready(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#getRequest').on('click', function () {
$.get('getMessages', function (data) {
$('#target').append(data);
});
});
});
</script>
I added the .ajaxSetup to make sure tokens are not the reason for this problem. So I typed in this .blade file also the following tag:
<meta name="csrf-token" content="{{ csrf_token() }}" />
Here is my route.php file:
Route::get('getMessages', 'PagesController#getMessages');
And here is my controller with the method in cause:
public function getMessages()
{
return "OK";
}
The problem is tricky to me, because I know that I can create a anonimous function in my route.php file for this URI and it's gonna be the same thing. Or not. I don't know because if I actually do this
Route::get('getMessages', function ()
{
return "OK";
});
instead of pointing to a method of a controller, it works! But I need it to work in a controller.
My controller is functioning properly when it comes to other methods and the name of the method is spelled correctly everywhere.
I'm working with XAMPP on Windows. I set XAMPP to work only with the current Laravel app, so when I type in "localhost" in my browser, it gets me to my app page and all of database data fetching work properly.
You should probably set your ENV to local so you can debug your code.
Maybe a faster solution for you would be for you to check the storage/logs/laravel.log and see the last stack trace so you can determine exactly where the error is coming from.

Permanently change html file using AJAX call on node.js server

How do I write a script to permanently change a static html file after making an ajax call to the node.js server? Any examples would be greatly appreciated :)
I agree with NikxDa that this is probably not the best solution for you, but this code should do the trick.
/write.js
var http = require('http');
var fs = require('fs');
var url = require('url');
//Lets define a port we want to listen to
const PORT=8080;
function handleRequest(request, response){
var path = url.parse(request.url).pathname;
if(path=="/write"){
fs.appendFile('message.html', 'Node.js!', function (err) {
if (err) throw err;
console.log('It\'s saved!');
});
} else {
fs.readFile('index.html',function (err, data){
response.writeHead(200, {'Content-Type': 'text/html','Content-Length':data.length});
response.write(data);
response.end();
});
}
}
// Create a server.
var server = http.createServer(handleRequest);
server.listen(PORT, function(){
console.log("Server listening on: http://localhost:%s", PORT);
});
/index.html
<!DOCTYPE html>
<head>
<script>
function writeIt()
{
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://localhost:8080/write", true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
string=xmlhttp.responseText;
document.write(string + ": Saved change to message.html");
}
}
xmlhttp.send();
}
</script>
</head>
<body>
<p>Click the button to send an AJAX request to `write.js`<p>
<br><button onclick="writeIt()">Click Me</button>
</body>
/message.html
Node.js!
Editing the file directly via node would probably be really bad, I do not even know if it is at all possible. I think the better solution is for your Node Server to make the data you want to change accessible and then use jQuery or Angular to update the HTML-File when it is actually loaded.
Another approach would be to use a templating engine like https://github.com/tj/ejs, and then serve the file via Node directly, so you can change the data in the Node-Application itself every time.

$http error handling: distinguishing user offline from other errors

I have a simple contact form, which Angular submits via AJAX to my app on Google App Engine. (A POST handler uses the send_mail function to email the website owner). This is the client code:
$http.post('', jQuery.param(user), {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function(data, status, headers, config) {
//...
}).error(function(data, status, headers, config) {
alert('Please check your Internet connection and try again.');
});
Obviously the alert() is handling all errors. Assuming no errors in my server-side code, I'm guessing the chances of App Engine returning anything other than an HTTP status code of 200 is low. However I would still like to distinguish between server errors and the user having lost their connection.
I was thinking of using XMLHttpRequest's textStatus as per this SO answer, but it doesn't appear to be available to the $http.error() callback. I also thought of using Offline.js but I don't need most of what it does so that would seem like wasted bytes in this case.
The $http.error() status I get when offline is 0, but I'm not sure how cross-browser reliable that's going to be. What should I be using?
Before giving you the solution I just wanted to highlight the problems with browser provided is-offline flag
Different browser's offline flag has different meanging
a. for some browsers it means internet is not there
b. for some browsers it means intranet is not there
c. some browsers do allow offline mode, so even if there is no internet, you are not actually offline.
not all browsers support offline in consistent way
Another problem I had with using browser based flag is development scenario, where having internet is not necessary, and that should not trigger the offline mode (for me I block all user interaction If my website goes offline). You can solve this problem by having another indicator telling you if you are in dev/prod, etc.
And most imp part, why do we care to find if browser is in offline mode, is because we do care only if our website is reachable or not, we don't actually care if the internet is there or not. So even if browser tell us it is offline, it is not exactly what we want. there is a tiny difference between what we want and what browser provides.
So considering all of above, I have solved the problem using an offline directive which I am using to block user interaction if user is offline
csapp.directive('csOffline', ["$http", '$interval', "$timeout", "$modal", function ($http, $interval, $timeout, $modal) {
var linkFn = function (scope) {
scope.interval = 10; //seconds
var checkConnection = function () {
$http({
method: 'HEAD',
url: document.location.pathname + "?rand=" + Math.floor((1 + Math.random()) * 0x10000)
})
.then(function (response) {
$scope.isOnline = true;
}).catch(function () {
$scope.isOnline = false;
});
};
scope.isOnline = true;
$interval(checkConnection, scope.interval * 1000);
scope.$watch('isOnline', function (newVal) {
console.log("isOnline: ", newVal);
//custom logic here
});
};
return {
scope: {},
restrict: 'E',
link: linkFn,
};
}]);
I was about to use offline.js, it was too much and most of which I didnt need, so this is the solution I came up with which is purely in angular.js.
please note that http interceptor is invoked during these calls, I wanted to avoid that, hence I had used $.ajax for the calls
$.ajax({
type: "HEAD",
url: document.location.pathname + "?rand=" + Math.floor((1 + Math.random()) * 0x10000),
contentType: "application/json",
error: function () {
scope.isOnline = false;
},
success: function (data, textStatus, xhr) {
var status = xhr.status;
scope.isOnline = status >= 200 && status < 300 || status === 304;
}
}
);
you can replace the logic inside isOnline true/false, with whatever custom logic you want.
I'd go with response.status === 0 check. I've tested it using the code below (needs to be put on a webserver that you can switch on/off at will) and I'm getting 0 in current versions of Google Chrome, Mozilla Firefox, and Internet Explorer. You may use it to test all browsers you want to support.
Code for testing connection status:
<!DOCTYPE html>
<html>
<head>
<title>Connection status test</title>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
<script type="text/javascript">
var log = [],
pendingCount = 0,
pendingLimit = 5;
angular.module('app', [])
.run(function ($rootScope) {
$rootScope.log = log;
})
.run(function ($http, $interval, $rootScope) {
$interval(function () {
if (pendingCount >= pendingLimit) {
return;
}
var item = {
time: Date.now(),
text: 'Pending...'
};
++pendingCount;
$http.get('.', {})
.then(function () {
item.text = 'Done';
}, function (response) {
item.text = 'Done (status ' + response.status + ')';
})
.finally(function () {
--pendingCount;
});
log.unshift(item);
}, 1000);
});
</script>
<style rel="stylesheet" type="text/css">
ul {
list-style: none;
padding: 0;
}
</style>
</head>
<body ng-app="app">
<ul>
<li ng-repeat="item in log">{{item.time | date:'HH:mm:ss'}}: {{item.text}}</li>
</ul>
</body>
</html>
try this one
$http.post('', jQuery.param(user), {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).complete(function(data, status, headers, config) {
//...
});

Clear IE cache when using AJAX without a cache busting querystring, but using http response header

I'm having the classic IE-caches-everything-in-Ajax issue. I have a bit of data that refreshes every minute.
Having researched the forums the solutions boil down to these options (http://stackoverflow.com/questions/5997857/grails-best-way-to-send-cache-headers-with-every-ajax-call):
add a cache-busting token to the query string (like ?time=[timestamp])
send a HTTP response header that specifically forbids IE to cache the request
use an ajax POST instead of a GET
Unfortunately the obvious querysting or "cache: false" setting will not work for me as the updated data file is hosted on Akamai Netstorage and cannot accept querystrings. I don't want to use POST either.
What I want to do is try send an HTTP response header that specifically forbids IE to cache the request or if anyone else knows another cache busting solution??
Does anyone know how this might be done? Any help would be much appreciated.
Here is my code:
(function ($) {
var timer = 0;
var Browser = {
Version: function () {
var version = 999;
if (navigator.appVersion.indexOf("MSIE") != -1) version = parseFloat(navigator.appVersion.split("MSIE")[1]);
return version;
}
}
$.fn.serviceboard = function (options) {
var settings = { "refresh": 60};
return this.each(function () {
if (options) $.extend(settings, options);
var obj = $(this);
GetLatesData(obj, settings.refresh);
if (settings.refresh > 9 && Browser.Version() > 6) {
timer = setInterval(function () { GetLatestData(obj, settings.refresh) }, settings.refresh * 1000);
}
});
};
function GetLatestData(obj, refresh) {
var _url = "/path/updated-data.htm";
$.ajax({
url: _url,
dataType: "html",
complete: function () {},
success: function (data) {
obj.empty().append(data);
}
}
});
}
})(jQuery);
Add a random number to the GET request so that IE will not identify it as "the same" in its cache. This number could be a timestamp:
new Date().getTime()
EDIT perhaps make the requested url:
var _url = "/path/updated-data.htm?" + new Date().getTime()
This shouldn't cause any errors I believe.
EDIT2 Sorry I just read your post a bit better and saw that this is not an option for you.
You say "is hosted on Akamai and cannot accept querystrings" but why not?
I've never heard of a page that won't accept an additional: "?blabla", even when it's html.
This was driving me crazy. I tried many cache busting techniques and setting cache headers. So many of these either did not work or were wild goose chases. The only solution I found which tested to work correctly was setting:
Header Pragma: no-cache
I hope it saves others with IE headaches.

Looking for an extremely simple AJAX script

I need a very basic, simple and lightweight AJAX script.
Does anyone have a shell of such a script they can share?
Here's what I have:
I have a PHP script on the server that echo's the current date and time on the server
I just need the javascript that calls the php script and loads the echoed text string into a js var so I can use it in my app
(the reason I need the server's clock is that all visitors to the site have to work off the same clock. The app does not work for visitors outside the server's timezone.)
Thanks for helping out.
JQuery is perhaps the right answer for AJAX but you can also do this in plain old Javascript as follows:
<html>
<head>
<script type="text/javascript">
function loadXMLDoc(){
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//the callback function to be callled when AJAX request comes back
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
  }
}
xmlhttp.open("POST","<<url of web address>>",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>
</body>
</html>
You can find a simple example here:
AjaxCall = function(Data, WebServiceURL, Callback) {
var request;
var url = WebServiceURL;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
Callback(request);
} else {
alert("Sorry, an error occurred. " + request.responseText);
}
}
};
request.open("POST", url, true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.send(Data);
} else if (window.ActiveXObject) {
url += "?" + Data;
request = new ActiveXObject("Microsoft.XMLHTTP");
if (request) {
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
Callback(request);
} else {
alert("Sorry, an error occurred. " + request.responseText);
}
}
};
request.open("GET", url, true);
request.send();
}
}
};
The the ajax functionality in jQuery is great but does mean a greater page download for one simple Javascript function.
You can find a downloadable fully worked example on my blog here:
http://www.willporter.co.uk/blog/simple-ajax-script.aspx
It uses ASP.NET on the server side but you should get the idea.
jQuery has made very simple ajax methods for you to use. You can find more information about them here.
Sample:
$.ajax({
type: 'GET',
url: '/SomeUrl/On/The/Server',
data: { SomeValue: 10 },
success: function(data, status)
{
// On Success
},
error: function(data, status)
{
// On Error
}
});
Look into this maybe : http://www.scriptiny.com/2011/01/simple-ajax-function-example/
jQuery is a more reliable library overall, but the lightest-weight AJAX methods I have found are the extremely simple Feather AJAX, coming in at 1.6 KB (with room for compression), or a one-liner snippet that I can't guarantee.
The risk of extremely lightweight libraries is that if they break, you're relying on the owner to fix it instead of a team of developers.
An alternative approach to solving your problem is to based your times on UTC instead of server-local time. You can even show the client local times based on that utc time, with a little work.
May I suggest AJAX Generator?
I am developer, and it is commercial tool but it has demo as well.
What you could do with that tool is:
put annotation on your PHP function
run AJAX Generator on PHP source file
include generated JavaScript file in HTML page and use PHP service as if you were calling function
To make it more clear, here is example code:
//example.php
<?php
//#WebService
function getServerDate(){
return date('m/d/Y h:i:s a', time());
}
?>
Now run generator on: example.php
Output would be two files: example_service.php and example_caller.js
Now you need to:
add example_service.php in same directory where is example.php and
include example_caller.js in index.html
Sorry for posting image instead of HTML code, but it wasn't showing properly.

Resources