Skip to content

Why JSON data structures are good for you when using AJAX

Below is a real good reason to compile a well-formed JSON data structure if you are about to send data through ajax with jquery, as sometimes (like today of course) you can receive undesirable and unexpected results if you take the cheap and nasty option of a simple serialised data string. I thought this is all I would need:


data: "article="+article+"&header="+header+"&content=my+content"+content

But how I was wrong!

So my actual problem. It lied with attempting to pass a simple plus sign (“+”) through AJAX; my data was coming through okay, however the plus sign was being converted to a space (” “) on the other end! Very odd – somewhere down the line, something was changing my data!

So after contemplating life, trees, the world and that weird banana exploding.. disturbing, demonstration, thing.. I came to the simple realisation that JQuery or http was sprinkling it’s helpy helpfulness dust all over the place, and taking the liberty of doing these html encodes on my data voluntarily, and this is what was causing my plus to be a space.

So I knew my problem. I was passing a raw url basically of data and expecting it to be the same, of course it wouldn’t know exactly how to treat it as it would have to be html encoded. So after a little bit of research it all came clear once I read this JQuery support ticket:
http://dev.jquery.com/ticket/2239

It made complete sense, obviously now having my data defined as JSON “data” tag, I would be explicitly telling the engine what my data actually was and not to touch it.

Much cleaner.

So for those that don’t like to click things, in essence changing this:
[sourcecode language='javascript']
data: “article=”+article+”&header=”+header+”&content=my+content”+content

To this:
[sourcecode language='javascript']
data: {
article : $("#article").val(),
header : $("#header").val(),
content : $("#content").val()
}

Solved my problem and made all the difference. Now I can pass any characters, joy!

VN:F [1.9.1_1087]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.1_1087]
Rating: 0 (from 0 votes)
Bookmark and Share
kick it on DotNetKicks.com
Shout it

NOW, FOR A WORD FROM OUR SPONSORS

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*
My name is Graham O'Neale and I'm a software architect from Gold Coast, Australia. I am an overtime thinker, full time coder and awake part time in the real world. I have a keen interest in software development, particularly in the realm of programming (C#, ASP.NET, ASP.NET MVC, LINQ (2 SQL), Entity Framework, Silverlight, Blend, WCF, WPF) and a keen interest in the cutting edge and innovation. I have a new found love for design patterns, ALT.NET practices and well crafted software architecture. The purpose of this blog is to express any thoughts, findings, tips and gripes along my travels in the wonderful world of coding and technology...