1

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.

1
  • What browsers do you have to support? That whole thing on top is really crufty and is useful to support browsers like IE6 and IE5.5 which I doubt you actually have to support. Please clarify on that. Commented Dec 21, 2014 at 11:15

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

5 Comments

I am not sure if I undstand you correctly. Do you mean the xmlhttp.onreadystatechange = CreateXmlElement; should be written before the "open"?
@Xshibi I've updated my answer, but I have to admit that it's a little unclear what you're trying to do. As far as I can tell: 1) get file from server, 2) modify XML, 3) post modified XML back to server.
Thank you for your answer but it is still not working. I am basically trying to create a chat system for my school project. The problem is that when the user(me) trying to send a message to another user, the message does not add to the xml file that contains the conversation. So I created a mini project just to solve this problem.
@Xshibi Are you saving the posted XML file again on the server side at all?
That save function does not work in javascript, and i thought the post saves the file. Do you have any idea how should i solve it?
0

This construct works for me. It opens a xml file, changes one Tag and saves it back to the server.. HTML part:

<!DOCTYPE html>
  <html lang="en">
    <head>
      <meta charset="utf-8">
      <title>xml </title>
    </head>
    <body>
    <div id="xml_tag0" >
      zero  
    </div>  
    <div id="xml_tag" >
      Start!!  
    </div>
    <div id="xml_tag2" >
      Start!!  
    </div>
    </body>
    <script type="text/javascript" src="./js/jquery.min.js"></script>
    <script type="text/javascript" src="./js/test_xml_load_and_save.js" charset="utf-8"></script>
  </html>

The JavaScript Part(test_xml_load_and_save.js):

      $.ajax({
      type: 'GET',
      url: '../php/B.xml',
      dataType: 'text',
      success: function(xml){

            doc = $.parseXML(xml)
            $('#xml_tag').text($(doc).find('row FIELD2').eq(2).text());  
            console.log($(doc).find('row FIELD2').eq(2).text());    
            $(doc).find('row FIELD2').eq(2).text('50%');

            xml = (new XMLSerializer()).serializeToString(doc);

            //var dataString = '<test></test>';
            var dataString = xml; 
            $('#xml_tag0').text(xml);

            $.ajax({  
            type: 'POST',
            url: '../php/ToXML.php',          
            contentType: "text/xml",
            dataType:'text',
            data: {xml : dataString},
            cache: false,
            success: function(response) {
                console.log(response);
                $('#xml_tag2').text(response);
            },
            success: function(data){
                console.log('LOG success: '+data); 
                $('#xml_tag2').text('LOG success: '+data);
            } 
            });



      }});

and the PHP part (php/ToXML.php):

      <?php
      header('Content-Type: text/html; charset=UTF-8');


      $data = $_POST['xml'];
      $xml = file_get_contents('php://input');
      $xml = rawurldecode($xml);
      $xml = str_replace('+', '', $xml);
      $xml = str_replace('xml=', '', $xml);
      //echo ":".$xml;
      $xml = '<?xml version="1.0" encoding="UTF-8"?>' . $xml;

      $filename = "B.xml";
      $f = fopen($filename, 'w+');
      fwrite($f, $xml);
      fclose($f);
      echo "Ok";
      ?>

the XML file:

 <?xml version="1.0" encoding="UTF8"?>

  <root>
  <row>
  <FIELD1>Cat1</FIELD1>
  <FIELD2>Min</FIELD2>
  <FIELD3>Neutral</FIELD3>
  <FIELD4>Max</FIELD4>
  </row>


  <row>
  <FIELD1>Liquid</FIELD1>
  <FIELD2>0%</FIELD2>
  <FIELD3>7%</FIELD3>
  <FIELD4>65%</FIELD4>
  </row>


  <row>
  <FIELD1>Bonds</FIELD1>
  <FIELD2>25%</FIELD2>
  <FIELD3>50%</FIELD3>
  <FIELD4>70%</FIELD4>
  </row>


  <row>
  <FIELD1>Equities</FIELD1>
  <FIELD2>10%</FIELD2>
  <FIELD3>25%</FIELD3>
  <FIELD4>35%</FIELD4>
  </row>


  <row>
  <FIELD1>AltInv</FIELD1>
  <FIELD2>0%</FIELD2>
  <FIELD3>18%</FIELD3>
  <FIELD4>30%</FIELD4>
  </row>

  </root>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.