Loading...

How do I use jQuery/REST/JSON with the WORKetc service? #7

In addition to /Xml service endpoint, we also support a /Json endpoint which can be used by scripting languages or folks inexperienced with SOAP, XML or OOP in general.

Below is an example of how to authenticate and log a timesheet (Event of type 'Journal') using jQuery:

//
// Original from http://code.google.com/p/jquery-json/
// (Modified to work with ASP.NET json deserialiser)
//
(function($) {
var m = {
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"': '\\"',
'\\': '\\\\'
},
s = {
'array': function(x) {
var a = ['['], b, f, i, l = x.length, v;
for (i = 0; i < l; i += 1) {
v = x[ i ];
f = s[typeof v];
if (f) {
v = f(v);
if (typeof v == 'string') {
if (b) {
a[a.length] = ',';
}
a[a.length] = v;
b = true;
}
}
}
a[a.length] = ']';
return a.join('');
},
'boolean': function(x) {
return String(x);
},
'null': function(x) {
return "null";
},
'number': function(x) {
return isFinite(x) ? String(x) : 'null';
},
'object': function(x) {
if (x) {
if (x instanceof Array) {
return s.array(x);
}
// Special JSON date hack for MS based service
if (x instanceof Date) {
return '"\\\/Date(' + x.getTime() + ')\\\/"';
}
var a = ['{'], b, f, i, v;
for (i in x) {
v = x[ i ];
f = s[typeof v];
if (f) {
v = f(v);
if (typeof v == 'string') {
if (b) {
a[a.length] = ',';
}
a.push(s.string(i), ':', v);
b = true;
}
}
}
a[a.length] = '}';
return a.join('');
}
return 'null';
},
'string': function(x) {
if (/["\\\x00-\x1f]/.test(x)) {
x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
var c = m[ b ];
if (c) {
return c;
}
c = b.charCodeAt();
return '\\u00' +
Math.floor(c / 16).toString(16) +
(c % 16).toString(16);
});
}
return '"' + x + '"';
}
};

$.toJSON = function(v) {
var f = isNaN(v) ? s[typeof v] : s['number'];
if (f) return f(v);
};

$.parseJSON = function(v, safe) {
if (safe === undefined) safe = $.parseJSON.safe;
if (safe && !/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(v))
return undefined;
return eval('(' + v + ')');
};

$.parseJSON.safe = false;

})(jQuery);



//
// Method to perform a login, calls RecordTime if successful.
//
function LoginAndDoStuff(domain, email, pass)
{
// Construct login paramaters (see /Xml?op=AuthenticateWebSafe for docs)
var request = new Object();
request.email = email;
request.pass = pass;

$.ajax({
url: 'http://' + domain + '/Json/AuthenticateWebSafe',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: $.toJSON(request),
success: function(result)
{
if (result.Code==1)
{
RecordTime(domain, result.SessionKey);
}
else
{
alert(result.Message);
}
}
});
}


//
// Recording a timesheet
//
function RecordTime(domain, veetroSession)
{
// Construct Event entry class (see /Xml?op=SetEvent for docs)
var e = new Object();
e.EntryID = 0; // 0 denotes a new entry!
// Event types are {ToDo: 0,Journal: 1,Event: 2}
e.EventType = 1;// Journal = "timesheet",
e.CalendarID = 1; // stick it on the system "work" calendar (always calendar ID 1)
e.Name = "Timesheet title";
e.DescriptionHtml = "Extended details here if you like..";
e.Owner = new Object();
e.Owner.EntityID = 1; // Owner is the Employee/Creator
e.Activity = 1; // Activity ID (see Get/SetActivity(..) web methods)
e.DateStart = new Date(new Date()-60*60*1000); // let's pretend 1hr timesheet
e.DateEnd = new Date(); // ending now..
e.Relation = new Object();
e.Relation.EntityID = 2; // Relation is your Customer
e.EntryID_Parent = 0; // If you have a project or some other thing, put it's ID here
// Entry flags are: {Billable: 1,Invoiced: 2,Journal: 4,Canceled: 8,Project: 16,Calendar_Item: 32,Event: 64,ToDo: 128,Support_Case: 256,Product: 512,Subscription: 1024,Notifications_Sent: 2048,Disbursement: 4096,Client_Access: 8192,QuoteOnly: 16384,Track_Supplier_Payments: 32768,All_Employees: 65536,Project_Milestone: 131072,Never_Invoice: 262144}
e.Flags |= 1; // We want to flag it billable.

// Now send our timesheet request
var request = new Object();
request.e = e;


$.ajax({
url: 'http://'+domain+'/Json/SetEvent?VeetroSession='+veetroSession,
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: $.toJSON(request),
success: function(result)
{
alert("Timesheet logged, entry id was "+result.EntryID);
},
error: function(request, error) {
alert("If you get an error here you probably don't have webservice enabled or permission to log timesheets.");
}
});
}




LoginAndDoStuff('YOURDOMAIN!.worketc.com', 'user@domain.com', 'yourpass');


</script>


WORKetc supports the HTTP "OPTIONS" Access-Control-Allow-Origin header which allows browsers to utilise the service cross-domain. As always, you need to enable webservice access for any of this to work. Unfortunately that means you'll probably need to enable global access to your web service to use the JSON end-point.