Unleashing the power of XPath and wildcards in AJAX

Can anyone explain why the variable objProperties, which contains an xpath with a wildcard, is coming up empty in this scenario?

function getXMLServerObject (httpType, cmd, isAsync) {
    var object = new Array();
    $.ajax({
      type: httpType,
      url: cmd,
      async: isAsync,
      dataType: "xml",
        success: function (xml) {
          var error = $(xml).find("Error");
          if (error == null) {
              object["__error"] = error.text();
              return object;
          }
          var objProperties = $(xml).find("Data\\Record\\*");

This results in an empty array for xml:

...

<Data>
    <Record>
        <MailFrequency>30</MailFrequency>
        <Tracking>-1</Tracking>
    </Record>
</Data>

However, searching for individual nodes returns the expected results.

Answer №1

jQuery does not support XPath selectors by default.

When you convert XML into a jQuery object, treat the tags like you would HTML tags and use the same jQuery selector methods.

If you have multiple <Record> elements, you can try this:

var $records = $(xml).find("Record"); /* create a collection of all Record tags */

$records.each(function(){
  var $children=$(this).children();
   /* or to access specific elements*/
   var mailFreq= $(this).find('MailFrequency').text();
})

Answer №2

When examining the code

var objProperties = $(xml).find("Data\\Record\\*");

It seems that the XPath expression "Data\\Record\\*" is being used, although it is unusual to have \ as a separator in XPath. Typically / is used: "Data/Record/*".

In addition, you can achieve the same result with jQuery selectors, which are an extension of CSS3 selectors. Remember that the root node is Data and $.find only searches among children:

var objProperties = $(xml).find("Record > *");

This will not create proper objects for the elements inside each record. To accomplish that, you should follow charlietfl's approach with some adjustments.

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

Error: The window object is not found in this context when initializing the Commerce module from the commerce.export.js file located in the node_modules folder within the @chec

I have been working with the pages router and custom app file (_app.js) https://nextjs.org/docs/pages/building-your-application/routing/custom-app It seems that the issue may be within my _app.js file, where I have the following code: import '../glo ...

Continuously encountering the "Uncaught Error: Bootstrap dropdown requires Popper.js" message despite having already added popper.js to the code

Recently beginning my journey with Angular and Bootstrap, I decided to create a simple "hello world" app. I've included all the necessary libraries, but I encountered an error that has me stuck. Error: Bootstrap dropdown requires Popper.js I' ...

The head.js feature similar to "Modernizr" does not recognize ms-edge

It has come to my attention that the head.js script is unable to detect the Microsoft "Edge" browser correctly. In addition, it erroneously adds classes like chrome and chrome55 to the <html> element. Is there a better way to handle this issue? The ...

retrieving form data from a submit button using objects in PHP

I am using objects to fetch a form (including a submit button) from another page. However, I am struggling to extract the POSTED information from that submit button and believe that AJAX might be necessary. Here is an example: Page 1 initiates a call to ...

Using NicEdit for uploading to your personal server

I'm having trouble uploading images using the NicEdit WYSIWYG editor on my own server. When I click on the upload image button, it redirects me to another site where I can upload the image: imgur dot com You can find a demo of this here: However, I ...

What is the process for including a new item in an array of objects?

const data = [ { title: 'Tasks', items: ['complete assignments', 'study for exams'], }, { title: 'Ongoing', items: ['learn new skills', 'work on projects'], }, { titl ...

Getting the specific nested array of objects element using filter in Angular - demystified!

I've been attempting to filter the nested array of objects and showcase the details when the min_age_limit===18. The JSON data is as follows: "centers": [ { "center_id": 603425, "name" ...

The key property is present on the list item, yet the key warning persists

I have encountered various issues with this problem, but I am unable to pinpoint the exact cause. I am not extracting individual list items and simply displaying a UL with unique keys assigned to each item. However, when I log the results, I see something ...

Is there a way to execute PHP scripts using JQuery or AJAX without causing the page to refresh?

REFRESHED CODE I'm attempting to execute PHP scripts within my main PHP file where all content will be presented. My goal is to exhibit the outcomes from my PHP script including the SQL queries in use. I also aim to implement the feature of showcasin ...

What is the best way to apply a class to an element in an input template using Angular's ngFocus directive, or any directive incorporated in the Ionic Framework?

I'm working with a template that looks like this: <label class="item item-input" ng-class="{'focus':authData.username.focus}"> <--add class here if input:focus <span class="input-label">Username</spa ...

What is the best way to convert JavaScript to JSON in Python programming?

I encountered a situation where I have an HTML page that contains a lengthy product list, making it too large for me to upload. The products are stored within the script section of the page, specifically in one variable. Initially, I mistook this data for ...

Ways to invoke a function in Angular2 when the Boolean condition is met

Within my component class, I have implemented a popup function along with a Boolean flag that returns true or false based on specified conditions. In the template class, I want the popup function to be triggered when the flag becomes true, displaying a pop ...

TS: How can we determine the type of the returned object based on the argument property?

Assume we have the following data types type ALL = 'AA' | 'BB' | 'CC'; type AA = { a: number; }; type BB = { b: string; }; type CC = { c: boolean; }; type MyArg = { type: ALL }; I attempted to create a mapping between type n ...

Leveraging server-side data with jQuery

When my client side JQuery receives an array of JSON called crude, I intend to access and use it in the following way: script. jQuery(function ($) { var x = 0; alert(!{JSON.stringify(crude[x])}); ...

After redirection to a new page, the Ionic-vue menu malfunctioned

I have developed a reusable header component named Header, which contains an IonMenu component for consistency across pages. The menu is associated with the IonRouterOutlet as per the documentation, but I am encountering an issue when navigating between pa ...

Deactivate DropDownList within Update Panel with JQuery

Below is the Update Panel that I am working on: <asp:ScriptManager ID="ScriptManager1" runat="server" /> <asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server"> <Triggers> <asp:AsyncPostBackTrigger ControlID="d ...

What is the process for inserting or removing a row with Javascript?

Currently, I am in the process of working on some HTML/PHP code which is displayed below. <h3 style="text-align:center;margin-top:45px;">Sitting Days</h3> <div class="sitting-days" style="display:flex; justify-content:center; margin-bottom ...

Make sure the auto import feature in TypeScript Visual Studio Code Editor is set to always use the ".js" extension

At times, the auto-import completion feature includes the .js extension, but inconsistently. When this extension is missing in the TypeScript source, the emitted JavaScript file may encounter runtime issues like module not found error since the tsc compile ...

Show a dynamic Swiper carousel upon selecting a thumbnail in an image gallery

I am in the process of creating a thumbnail gallery that includes a slider feature using Swiper. The default setup has the slider hidden, and once an image is clicked, the slider should appear with the selected image. To close the slider and return to the ...

JAVASCRIPT ENCOUNTERS ISSUE WITH RANDOM TEXT GENERATION

Utilizing an array of words, we are in the process of generating random text. The goal is to shuffle and combine these words to form new "random sentences". However, we have encountered a minor issue - the addition of "undefined" at the beginning of each p ...