Reading XML and trying to insert in localSQLDB via javascript
Hi,
I'm currently learning myself to build an HTML5 app with JQmobile and Jquery that later will be turned into a app via Phonegap. I've recently started to play with reading in items from a xml which then are supposed to be put into the local SQL lite db that you get access to in HTML5.
The problem I have is that I do not seem to be able get the INSERT into the DB to work. I know I can read my XMl as I am able to output the contents fine on the page but when i use the same variable for the DB insert it just inserts the last item in the XMl over and over again.
My XML is very small and looks like this:
-
- <?xml version="1.0" encoding="utf-8" ?>
- <NobelLaureates>
- <Laureates>
- <Name>Spock</Name>
- <Category>Chemistry</Category>
- <Year>2010</Year>
- </Laureates>
- <Laureates>
- <Name>Kirk</Name>
- <Category>Economics</Category>
- <Year>2010</Year>
- </Laureates>
- <Laureates>
- <Name>Picard</Name>
- <Category>Physics</Category>
- <Year>2010</Year>
- </Laureates>
- </NobelLaureates>
my javascript-file that gets the xml and works on it looks like this:
- $(document).ready(function()
- {
- $.ajax({
- type: "GET",
- url: "link_to_my_xml
- success: function(xml) { parseXml(xml); }
- });
- });
- function parseXml(xml)
- {
- var db = openDatabase('LaurDB', '1.0', 'LaurDB', 2 * 1024 * 1024);
- db.transaction(function (tx) {
- tx.executeSql('CREATE TABLE IF NOT EXISTS laureates (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT, category TEXT, year INT)');
- tx.executeSql('DELETE FROM laureates');
- });
-
- var Name = "";
- var Category = "";
- var Year = "";
- //Create a SQL-database with all the info about the laureates
- $(xml).find("Laureates").each(function()
- {
-
- Name = $(this).find("Name").text();
- Category = $(this).find("Category").text();
- Year = $(this).find("Year").text();
-
- //alert("namn:" + Name);
-
- $("#output").append(Name);
- $("#output").append(": " + Category + " " + Year +"<br />");
- db.transaction(function (tx) {
- tx.executeSql('INSERT INTO laureates (name,category,year) VALUES (?,?,?)',[Name,Category,Year]);
- });
-
- });
- }
The odd this is that the variable Name, Category and Year indeed seems to get the correct content from the XMl as the #output-div where I append the debug info correctly lists each of the persons in the xml. However, in the database I only get the info for the last person (Picard), however 3 times!. I'm a bit confused here. Is something wrong with my function to get the content of the XML? Why does it work to append the correct info to the #output-div but in the next rows the same variable hasn't the same name?
I'm sure there's an easy explanation but I think I'm too tired to think of it right now ....
thanks in advance for any help.