Monday, 24 August 2009

jQuery Ajax submissions and invalid characters (like single quotes)

I’ve recently posted about submissions to ASMX services using Ajax to allow asynchronous data transfer to the client in a browser.  This works pretty well, but I’ve come across a problem with a particular invalid character when using my method.  The apostrophe.


   1: $.ajax({   
   2:     url: "ReviewHandler.ashx",   
   3:     data: “{   
   4:         'name': '" + $("#ReviewerName").val() + "',
   5:         'location': '" + $("#ReviewerLocation").val() + "'
   6:     }",   
   7:     processData: true,       
   8:     type: "POST",   
   9:     beforeSend: function() { startSubmit(); },  
  10:     complete: function() { submitComplete(); },  
  11:     error: function(xhr, statusText, errorThrown) { alert(errorThrown); },  
  12:     success: function(data) { submitSuccess(data); }  
  13: });

And this works fine.  But if you have an ‘ in your data, then obviously you’re code is going to explode.  Worst part is that it’s not going to be immediately obvious.  Your error text will just give you an internal server error message and you’ll need to use something like fiddler to nail the real reason that it failed unless you have great exception handling.

Well it’s very easy to make your code much more robust.  JSON.js is a set of standard JSON methods that can be used to serialise your objects into JSON strings and escape all your characters correctly for you.  Using JSON.js, the former becomes the following:

   1: var myObj = { 
   2:     name: name: $("#Name").val(),
   3:     location: $("#Location").val()
   4: }
   6: $.ajax({
   7:     url: "ReviewHandler.ashx",
   8:     data: JSON.encode(myObj),
   9:     processData: true,
  10:     type: "POST",
  11:     beforeSend: function() { startSubmit(); },
  12:     complete: function() { submitComplete(); },
  13:     error: function(xhr, statusText, errorThrown) { alert(errorThrown); },
  14:     success: function(data) { submitSuccess(data); }
  15: });

It’s neater for sure, and cleaner.  The encode method will escape all the illegal characters and allow it to work nicely with ASMX web service parameters.

1 comment:

Fred Quimby said...

Nice. I had seen another technique of ajax submission in forms in a book over here

That was pretty cool too!