Friday, October 7, 2011

Oh, the melancholy

Thursday, July 21, 2011

JSON is undefined in older browsers

Came up with the following error today, while trying to make a generalized way to invoke WebMethods from client side, using IE7:

PageServiceRequest invoke failed: 'JSON' is undefined

while doing something along the lines of this:



function TextBoxValueChanged (successCallback, failureCallback, message) {
 try {
  var parms = [];
  for (var i = 2; i < arguments.length; i++) {
   parms.push(arguments[i]);
  }
  var options = {
   type: 'POST',
   contentType: 'application/json; charset=utf-8',
   data: JSON.stringify({
    typeName: 'Echo.App.Layouts.Benchmarking',
    methodName: 'BenchmarkingSaveMessage',
    args: parms}),
   dataType: 'json',
   url: '/_layouts/UserControlScriptMethod.aspx/PageServiceRequest',
   success: successCallback,
   error: failureCallback
  };
  $.ajax(options);
 }
 catch (e) {
  alert('PageServiceRequest invoke failed: ' + e.message);
 }
}



And after browsing the internet relentlessly, finally found the solution here, and seemed like a nice way to start this blog. Apparently, newer browsers have built-in JSON support, whereas older browsers do not (that would explain I hadn't come up with this error before). All you have to do is download the js for JSON (json2.js) and include it in your page / master page / user control. And you have victory.

The function I present may be a little sketchy, but it will all come clear in my next post, about generalizing WebMethod invocation from client side. Let's hope I find a blogging tool before that :)