Looking for an extremely simple AJAX script - ajax

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.

Related

get requests fail when cache manifest is applied

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.

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) {
//...
});

Trying to read a local text file in html page using ajax

Tried this code to read data from a local text file.
But I don't know why this is not working.
Could someone help me with this problem. I can see in most of the answers in stackoverflow, they say that this is working, but this is not working for me. do I have to install anything for this?
<!DOCTYPE html>
<html>
<head>
<script>
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");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","sample.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
The problem is that XMLHttpRequest will not read files from the local filesystem (otherwise malicious websites could read files on your desktop!). Here are some solutions:
Install a server on 127.0.0.1. For a quick and dirty solution, you can use Python's SimpleHTTPServer or the Node.js http-server package. For production, use Nginx or Apache.
Put your files on a web host, such as Github Pages.
You can only read local files on the server side without user interaction. If you want to read a client side file, you have to use an html interaction element like:
<input type="file" id="openselect" />
Otherwise, if your file is on the server side, you could use something like:
function getdatafromfile(filename) {
// Read annotation file. Example : %timeinstant \t %value \n
// Return an array of string
var arraydata
$.ajax({
type: "GET",
url: filename,
dataType: "text",
success: function(csv) {arraydata = $.csv.toArrays(csv,{separator:'\t'}); }
});
return arraydata;}

How to XMLHttpRequest in Wordpress?

I'm trying to send a variable to the server, using XMLHttpRequest.
I tested it on local on a non-Wordpress file and it works.
But on production, on my Wordpress file, the onreadystatechange AJAX status doesn't get to 200.
Is there anything I need to be aware when XMLHttpRequesting in Wordpress?
<script>
params = "parameter=" + value;
request.open("POST", "../myfile.php", true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", params.length);
request.setRequestHeader("Connection", "close");
request.onreadystatechange = function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
if (this.responseText != null)
{
console.log('Request completed');
}
else console.log("Ajax error: No data received")
}
else console.log("Ajax error: " + request.statusText );
}
};
request.send( params );
// 'request' is 'XMLHttpRequest()' or 'ActiveXObject("Microsoft.XMLHTTP")'
// depending on browser
</script>
To create the code I followed the 2nd example of my O'Reilly book.
Any suggestion'll be much appreciated!
Thanks
Ultimately there is nothing wrong with this script.
I think it was due to the work frame I was using (Roots theme for Wordpress).
I change it for Handcrafted and I solved the problem.

Resources