how to save the xml file with ajax and javascript

advertisements

I am trying to add an element to an xml file. I have checked the program with debugger and I saw it really adds the element to the xml file but when I stop the running the file didn't saved any changes. here is the javascript file:

var xmlhttp = LoadXMLHttp();
var xmlDoc=LoadXMLDoc("XMLFile.xml");;
function LoadXMLHttp() {
    var xmlHttp;
    if (window.XMLHttpRequest)
        xmlHttp = new XMLHttpRequest();
    else
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    return xmlHttp;
}
function LoadXMLDoc(FileName) {
    xmlhttp.open("GET", FileName, false);
    xmlhttp.send(null);
    return xmlhttp.responseXML;
}
function CreateXmlElement() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        newMessageElement = xmlDoc.createElement("message");
        newTextElement = xmlDoc.createElement("text");
        newText = xmlDoc.createTextNode("I am fine");
        newTextElement.appendChild(newText);
        newMessageElement.appendChild(newTextElement);
        x = xmlDoc.documentElement;
        x.appendChild(newMessageElement);
    }
}
function AddXMLElement() {
    xmlhttp.open("POST", "Default.aspx", true);
    xmlhttp.setRequestHeader("Accept", "text/xml");
    xmlhttp.onreadystatechange = CreateXmlElement;
    xmlhttp.send(xmlDoc);
}

And here is the xml file:

<?xml version="1.0" encoding="utf-8" ?>
<conversation>
  <message>
    <text>Hi</text>
  </message>
  <message>
    <text>How are you?</text>
  </message>
</conversation>

By the way:

  1. I don't know jquery or php but I do know asp.net

  2. If I change the open url to "XMLFile.xml", I get an error message that says "method not allowed".

  3. I have a button that activates the AddXMLElement() function.


You're executing the CreateXmlElement method as a callback to your AJAX post. So you modify your document after sending it to the server instead of before. That's why the modified document is not saved.

You probably want to do something like this:

function CreateXmlElement() {
    newMassageElement = xmlDoc.createElement("massage");
    newTextElement = xmlDoc.createElement("text");
    newText = xmlDoc.createTextNode("I am fine");
    newTextElement.appendChild(newText);
    newMassageElement.appendChild(newTextElement);
    x = xmlDoc.documentElement;
    x.appendChild(newMassageElement);
}
function AddXMLElement() {
    CreateXmlElement();

    xmlhttp.open("POST", "Default.aspx", true);
    xmlhttp.setRequestHeader("Accept", "text/xml");
    xmlhttp.send(xmlDoc);
}