PDA

View Full Version : Need help with Ajax response and element creation



riffla
03-20-2009, 09:19 AM
Hi

Need some help/advice here from someone familiar with Ajax

I have a Jsp/Servlet aplication in which there is a scenario where the user will select, lets say a category, from a select box. This triggers a javascript which makes an Ajax request to a servlet returning all sub categories related to the selected category. As it is right now, I'm returning the complete HTML code that renders the sub category select element (upon request completion there is a Prototype update of a div that inserts the response - new sub category select element), and it shows up just fine in the JSP page. But the strange thing is that it doesn't show up when I View Source. In other words it seems like that select element won't be a part of forthcoming submits.

A guess is that I need to create a DOM element and add it to the form in javascript, but I I'm not sure at all.

/R

jscheuer1
03-20-2009, 09:33 AM
Nothing added to a page via AJAX will appear in the 'view source' view of the browser. If your browser has a 'view generated source' view, it should appear in that. Also, if your browser has a DOM inspector, the added element(s) (as well as any hard coded to the page which haven't been removed) will appear in it as nodes.

As to an AJAX added element added to a form working in a form when that form is submitted - that's tricky because adding an element to a form (depending upon how it is done), even if it appears visually on the page in the desired place, and in the DOM (when inspected) in the desired place, may or may not be recognised as a valid element in the form when submitted.

The only way to know for sure is to test it. However, if the added element has a value or name that comes with it when imported (again, depending upon how it gets there), some browsers will not recognise them as valid form element attributes.

riffla
03-20-2009, 10:09 AM
Thanks for your quick reply.
It turned out to be a bit like I expected then...

Guess it would be a better solution then to have the select element in place from start - hidden it would be - and then, upon ajax request completion, I would populate the existing select element with DOM option elements (with values taken from response), or would I face the same problem then?

/R

jscheuer1
03-20-2009, 10:33 AM
My advice would be to try it out via the simplest method(s) available first. Make sure to test in at least IE, FF, and either GC or Safari. If it works in those, there really isn't too much need to worry about it.

If you encounter problems, then I would use the DOM to create or clone the node you want to add, and attach it to the form. Any attributes that you want to add to the node, use setAttribute(), if the ordinary method doesn't work.