Tips for Using AJAX and JavaScript to Save an XML File

My current task involves attempting to insert an element into an XML file. Upon inspecting the program with a debugger, I noticed that the element is successfully added to the XML file. However, when I stop the program from running, the changes are not saved to the file. Here is the JavaScript code snippet:

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

Below is the content of the XML file:

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

Additionally:

  1. I have familiarity with asp.net, but not jQuery or php.

  2. If I modify the open URL to "XMLFile.xml," an error message stating "method not allowed" appears.

  3. A button triggers the execution of the AddXMLElement() function.

Answer №1

When you are using the CreateXmlElement method as a callback for your AJAX post, make sure to modify your document before sending it to the server. This will ensure that the changes you make to the document are saved.

To achieve this, you can follow these steps:

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

Answer №2

I have found a reliable way to manipulate XML files by using this code snippet. It allows me to open an XML file, modify a specific tag, and then save the changes back to the server. Here is the HTML portion of the script:

<!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>

Here is the JavaScript portion of the code (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 = 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);
            } 
            });



      }});

Lastly, here is 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);
    
      $xml = '<?xml version="1.0" encoding="UTF-8"?>' . $xml;

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

Below is the content of the XML file being manipulated:

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

  <root>
... (Content of the XML file goes here)
  </root>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Top strategies for efficiently managing the loading of extensive PHP pages using Jquery, Ajax, HTML, and other tools

Hey there, I hope you're doing well in this new year. I've been working on a project that creates a "league table" using a large amount of data, similar to those seen in sports like football. The backend is built in PHP to process the data and d ...

Can you show me the method to import these ES6 exports? Are they specifically named exports or the default?

As I reviewed the code in the Material UI project, I came across a section that is exporting a variety of React Components: src/Dialog/index.js: export { default } from './Dialog'; export { default as DialogActions } from './DialogActions ...

Enhance D3 Version 6 Stacked Bar Chart with Spacing and Interactive Features

My bar chart lacks the spacing between bars that I intended to achieve, and the interactive tooltip doesn't show up when hovering over the bars. I could use some assistance with this. The purpose is to display the value of a specific color when hoveri ...

Encountering issues with formData in nextjs 13 due to incorrect data type

In my NextJS application, I am using the dataForm method to retrieve the values from a form's fields: export async function getDataForm(formData) { const bodyQuery = { ....... skip: formData.get("gridSkip") ...

Creating an X pattern on an HTML5 canvas and detecting intersections with a perimeter

I am currently developing a maze game using HTML 5. Below is the function I have implemented to draw an "X" on the canvas (the player will guide the X through the maze using touchpad). dim = 8; function rect(x,y,xdim){ ctx.beginPath(); ctx.moveT ...

Ensure that site content remains visible above the table when refreshing the Ajax Table

Whenever I update the table, the content above it ends up below the table. This is frustrating because the content should not be affected by the refresh. How can I resolve this issue? <!DOCTYPE html> <html> <head> <titl ...

What could be causing my difficulty in locating an HTML element using jQuery/JS string interpolation?

In my project, I have a set of div blocks each identified by a unique numerical id. For instance: One of the tasks in my project is to select the 29th element following a specific chosen element. For example, if I choose the first div with id 1, then I s ...

Refresh a div element automatically with information from a different webpage using jQuery

I've been attempting to automatically reload a page and fetch new data every 10 seconds, or even less. However, the codes I've tried so far have not been successful. Here is my current approach... // script // <script> $(document).rea ...

Failure to send serialized data via AJAX to the specified URL

After executing the SUCCESS function, I have confirmed that my values are accurate: serviceID=123&acceptAgreement=on The acceptAgreement field is an input checkbox. Despite this, the DB file does not show any updates. To troubleshoot, I attempted to ...

Having trouble getting the onClick event to trigger in ReactJS buttons

The buttons are not functioning as expected, allowing for the addition of positive, neutral, or negative feedback. Interestingly, when I added a default button using different syntax to add negative feedback, it worked. This suggests that there may be an ...

Stopping the AJAX request due to an extensive query string in Elixir Plug

When I make AJAX requests, I include 2 large query strings that are essentially Base64 encoded jpegs. However, when the camera is not high resolution, the AJAX request does not abort. Initially, I thought it was a Nginx problem because I received an error ...

Activate a monitoring pixel with a click of your mouse

I have a tracking pixel that is typically placed in the body of a "installation success" page: <img src="http://domain.com/adclick.php" width="1" height="1" border="0" /> However, I want to trigger this pixel when someone clicks on a download butto ...

Trigger form submission with validation using jQuery

How can I redirect a user to another page named "free.php" from the index page without changing the URL, using jQuery? Below is an example I have created: http://jsfiddle.net/jKHQe/ The checkbox validation works in the example, but I am unable to redir ...

Interacting with wpdb using AngularJS

I just started learning AngularJS and I'm eager to implement it on my WordPress website. My goal is to display a table with data from a database in my WordPress site, but I am encountering difficulties accessing the WordPress functions and variables. ...

Avoid refreshing the page upon pressing the back button in AngularJS

Currently, I am working on building a web application that heavily relies on AJAX with AngularJS. One issue I am facing is that when the user clicks the back button on their browser, the requests are being re-made which results in data having to be reloa ...

Debugging Node.js Routes in Visual Studio Code: A Step-by-Step Guide

My application is structured as follows: server.js router routes emails.js index.js In my index.js file, I define the route like this: module.exports = function (app) { app.use('/emails', require('./routes/emails& ...

Using Bootstrap multiselect, you can easily control the display of a second menu based on the selection in the first menu

On my website, I am working with two menus. When I select Abon from the first menu, it should display all li elements under the Abon optgroup (Abon-1, Abon-2). If I uncheck block in the second menu, those elements should disappear. The code consists of Sel ...

Trigger a modal from one sibling Angular component to another

My application utilizes an Angular6 component architecture with the following components: <app-navbar></app-navbar> <app-dashboard></app-dashboard> The Dashboard component consists of: <app-meseros> </app-meseros> < ...

PHP script output continuously responded with AJAX

Encountering an issue with the AJAX response from my PHP script... I've set up a "Status" div to display the response of the PHP script. It currently only shows the response once the entire script has finished, but I would like it to show each echo " ...

Using AngularJS: Implementing ng-include with a custom function

When using ng-include, I have encountered a peculiar issue. I am attempting to retrieve the template path by invoking a function defined in the controller that returns the path based on the parameter passed. Below is my code snippet: <tr ng-repeat="det ...