Showing posts with label jquery. Show all posts
Showing posts with label jquery. Show all posts

Friday, 9 December 2011

jQuery and dot notation

I'm still a relative noob when it comes to jQuery, so I'm picking bits up all the time. The latest nugget is related to a previous post on converting an HTML to JSON which included the parsing of nested structures.
When it comes to populating a form with a nested structure there is potential to fall into a rabbit hole. Thankfully in this case the foxes had scared off the rabbits before they had the chance to dig too deeply.
The original issue manifested itself upon requesting a JSON resource with nested structure from a service and populating a form. Almost the opposite of the post linked to above. I went through the process of ensuring the JSON was valid, the path in the document matched the dot notation of the form and that the field had a value associated with it. The source presented below is a simplified test case designed to isolate the issue. What you see here is a form that is populated when the button is clicked. It looks rather innocent, however the "meh.feh" field doesn't get populated; exactly what I had seen in the original issue.

Simplied Example:

jQuery is treating the "." as CSS notation not as a literal. The solution? Escape them with a double backslash.

Simple fix:

For more information check the jQuery FAQ

Tuesday, 6 December 2011

Convert HTML form to JSON and POST using jQuery

Reinventing the wheel is a pet hate of mine; I could list quite a few actually, but that's not the point of this post.  Sometimes it takes me so long to look for a wheel that I think has or should have already been invented that it would have been easier just to invent the wheel myself.

Recently I was playing around with jquery, pulling fields from a form and posting them as a JSON object to a set of services.  Nothing fancy, nothing difficult there.  However, when the data model started to mature beyond the most basic structure I soon realised I need an easy, repeatable way to pull structured/nested data from a a form and convert it into a JSON object prior to posting.

To create the following structure:


You will need to create the following references:


This is a complete working example that will parse the form, create the JSON obbject, POST it to a service and display the returned object in a table.



The form above will produce the following JSON.