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

The jQuery AJAX autocomplete result box is either too cramped or displaying numbers

I'm having some trouble setting up jQuery UI autocomplete with ajax in my project using CI 3.1.5. When I try to implement it, I either get a small result box or just the number of results. Here is my AJAX code snippet: $(".addClient").each(funct ...

What is the proper method for overriding styles in material-ui v5 for properties that are not present in the themes components?

Currently, I am customizing MuiDataTables using the adaptv4theme in the following manner: declare module '@material-ui/core/styles/overrides' { export interface ComponentNameToClassKey { MUIDataTable: any; MUIDataTableFilterList: any; ...

Display or conceal a YouTube video with a click

Q1) Is it possible to use JQuery on page load to detect the file name of an image and then dynamically position it on the page with CSS? Q2) What is the most efficient way to achieve this without embedding iframe code inside a specific div.icon element? ...

A guide on dynamically checking the checkbox values in each row of a table using JavaScript or jQuery

My table is dynamically populated with values from a database using the following code: var row = table.insertRow(i); i = i+1; // Insert new cells (<td> elements) at the 1st and 2nd position of the new <tr> element: var cell1 = row.insertCell ...

Custom input field in Material UI not communicating properly with Redux form

I am currently utilizing Material UI and React to implement a custom input field. While using redux form for form validation, I have encountered an issue where the onBlur and onFocus events are not being dispatched successfully. Interestingly, if I switch ...

Getting Started with the Basic Example of Redux-Router

Recently, I decided to give redux-router a try and wanted to run the basic example. However, when I tried running the command: npm start I encountered an error message that said: node: bad option: -r Being new to the JavaScript modern ecosystem, I&apos ...

Tips for Keeping a Responsive Image at the Forefront of a Text-Image Layout as You Scroll

I'm currently in the process of creating a website where text appears on the left side with an accompanying image on the right. The challenge I'm encountering is ensuring that as users scroll, the image adjusts dynamically based on the associated ...

Only one bootstrap collapse is visible at a time

Currently, I am using Bootstrap's collapse feature that displays content when clicking on a specific button. However, the issue I am facing is that multiple collapses can be open at the same time. I want to ensure that only one collapse is visible whi ...

I am unable to determine if I have already selected a List Item

My goal is to have a functionality where clicking on "Download Drivers" will open the list, and clicking again will close it. This should be achieved with onclick events only, no hover effects. Additionally, I want the list to remain open even if I click o ...

Using JavaScript/jQuery to tally characters

Here is the code snippet that I am currently working with: PHP <input style="color:red;font-size:12pt;font-style:italic;" readonly="" type="text" name="q22length" size="3" maxlength="3" value="50"/> <textarea onkeydown="textCounter(doc ...

Display a loading animation before the page loads upon clicking

$("#button").click(function(){ $(document).ready(function() { $('#wrapper').load('page.php'); }); }); <div id="wrapper"></div> <div id="button">click me</div> I would like to display a loading ic ...

Ways to refresh my $scope once new data is inserted into the SQL database

As I implement the angularjs/SQL technique to fetch data from a database, the code snippet below demonstrates how it is done: $http.get("retrieveData.php").then(function(response){ $scope.tasks = response.data.tasks; }) In addition, there is a functi ...

Issue with Ajax not sending query string to ASP.NET controller

I am currently working with an Ajax function that serializes data sent from my view into a query string. Here is the code snippet: UpdateFIConfig: function ($appForm) { var valid = $appForm.valid(); //if not valid the validate plugin will take ca ...

What could be causing the second switchMap to be triggered repeatedly upon subscription?

Check out the code snippet below for reproducing the issue: import { defer, BehaviorSubject, of } from "rxjs"; import { shareReplay, switchMap } from "rxjs/operators"; const oneRandomNumber = defer(() => of(Math.floor(Math.random() ...

Issue encountered when attempting to utilize filters with strapi V4 graphql and nextjs, functionality not working

Currently, I am using strapi V4 along with the graphql extension. Everything works fine when I use filters with variables in the graphql Playground. query getOrdersFilterList($searchstring: String!) { orders(filters: { customer: { contains: $searchstring } ...

Is it possible to use D3 for DOM manipulation instead of jQuery?

After experimenting with d3 recently, I noticed some similarities with jquery. Is it feasible to substitute d3 for jquery in terms of general dom management? This isn't a comparison question per se, but I'd appreciate insights on when it might b ...

The ng-controller directive fails to function on the content of Kendo tabstrip tabs

My ng-controller is not functioning properly for the kendo tabstrip tab content. Could you please review my code below? <!--tabstripCtrl.js--> angular.module('tabstripApp',[]); var app = angular.module('tabstripApp'); app.con ...

Run module following a POST request

I am currently working on integrating real-time information transmission through sockets using socket.io, along with push notifications sent via the OneSignal platform. However, I have encountered an issue where placing both functionalities in the same mo ...

When utilizing ajax on a nodejs server, session cookies remain unaffected

I have been struggling to change a session cookie after an asynchronous request, despite trying various methods. The code for my request is: $.ajax({ type: "POST", url: "/setStatus", data: { userId : _userId, token: _token, tokenSecret : _toke ...

Modifying a single route among several nested routes with specific names

My template includes various named, nested views: Template 1: <body> <div ui-view></div> </body> Template 2: <header></header> <div ui-view="left"></div> <div ui-view="canva ...