How do I save HTML form data to an XML file using JavaScript?

2.2k Views Asked by At

I am making a blog in which users can leave comments on my posts. I used JavaScript to read the data from the XML file and display it in a div element. However, I can't get the page to save new comments to the XML file, and then rewrite the div contents based on the changed XML file. I know how to edit the XML file, but how do I save it? (Sorry, the code's a little messy)

Source Code:

index.html:

<!DOCTYPE html>

<html lang = "en-US">

<head>

<title>Blog</title>

    <script src = "loadXML.js">

    </script>

    <script>

        function addComment1(form)

        {

        var xmlDoc = loadXMLDoc("one.xml");

        var use = form.user1.value;

        var com = form.comment1.value;

        }

    </script>

    <meta charset = "utf-8"/>

</head>

<body>

    <h1>Posts</h1>

    <br/>

    <!-- A Post -->
    <h2>Comments:</h2>

    <div>

        <p>

            <script>

                var xmlDoc = loadXMLDoc("one.xml");
                var cap = xmlDoc.getElementsByTagName("content");

                for (i = 0; i < cap.length; i ++)

                {

                    document.writeln(xmlDoc.getElementsByTagName("user")[i].firstChild.nodeValue + ":<br/>");

        document.writeln(xmlDoc.getElementsByTagName("content")[i].firstChild.nodeValue + "<br/><hr/>");


                }

            </script>

        </p>

        <form name = "form1">

            <input type = "text" name = "user1"/>

        <input type = "text" name = "comment1" />

            <input type = "submit" value = "Submit" onclick = "addComment1(this.form)"/>

        </form>

    </div>

</body>

</html>

one.xml:

<?xml version="1.0" encoding="utf-8"?>

<comment>

        <user>Gabe Rust</user>

        <content>Hello World!</content>

</comment>

loadXML.js:

function loadXMLDoc(filename)

{

if (window.XMLHttpRequest)

{

        xhttp=new XMLHttpRequest();

}

else // code for IE5 and IE6

    {

        xhttp=new ActiveXObject("Microsoft.XMLHTTP");

}

xhttp.open("GET",filename,false);

    xhttp.send();

return xhttp.responseXML;

}



function loadXMLString(txt)

{

    if (window.DOMParser)

{

parser=new DOMParser();

xmlDoc=parser.parseFromString(txt,"text/xml");

}

else // code for IE

    {

xmlDoc=new ActiveXObject("Microsoft.XMLDOM");

        xmlDoc.async=false;

xmlDoc.loadXML(txt);

}


    return xmlDoc;

}
0

There are 0 best solutions below