I need to send a lot of information from my website to my webserver. These information contain data (first name, last name, etc.) from several users.
Before I'll send these information with an AJAX request to the webserver, I have to extract them out of a table and organize them somehow.
Now I'm considering two different possibilities:
1: Organize the data in an XML document with JavaScript / jQuery and send it to the webserver or ...
XML document
<create>
<customer>
<first-name>foo</first-name>
<last-name>bar</last-name>
...
<customer>
</create>
2: store the data in a string an organize them later on the webserver with PHP.
string:
"first-name='foo';last-name='bar'"
I've already tried this to create a XML document ...
var xmlDocument = $.parseXML('<create/>');
var customer = xmlDocument.createElement('customer');
xmlDocument.documentElement.appendChild(customer);
var firstName = xmlDocument.createElement('first-name');
xmlDocument.documentElement.appendChild(firstName);
... but it wasn't really working out. I used xmlDocument.find('first-name') to check if it's built correctly but it failed. Perhaps I'm accessing the XML document wrong.
I've also tries to use jQuery.parseXML(); but it wasn't working either.
Well, what is the proper way to create / access a XML document, create / delete / edit nodes and textnodes and set / get attributes in JavaScript / jQuery.
Can you give me an advice which of my mentioned opportunity to use? Maybe there is even one I haven't considered yet. I'd appreciate it if you could add some sample code.
You should do something like
var xmlDocument = $('<create/>');
var customer = $('<customer/>');
xmlDocument.append(customer);
var firstName = $('<first-name/>').text('john');
xmlDocument.append(firstName);
Corresponding xml:
<create>
<customer></customer>
<first-name>john</first-name>
</create>
To find an element xmlDocument.find('first-name').text() fiddle here http://jsfiddle.net/YpfmD/
This is exactly how you'd create html elements (after all html is an XML)
if yu need to create element with attributes you can do
$('<name/>', { first: "john", second: "doe"});
//this creates <name first="jhon" second="doe"></name>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With