Xshibi
Xshibi

Reputation: 21

how to save xml file with ajax and javascript

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.

Upvotes: 1

Views: 4839

Answers (2)

user3242128
user3242128

Reputation: 1

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>

Upvotes: 0

Robby Cornelissen
Robby Cornelissen

Reputation: 97130

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);
}

Upvotes: 1

Related Questions