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: Unable to access the 'wsname' property of an undefined value

I am attempting to retrieve values from a database using the code below (login.js) $.post("http://awebsite.com/app/login.php",{ rep1: rep, password1:password}, function(data) { if(data=='Invalid rep.......') { $('input[type="text"]').c ...

Why isn't this code for hiding the animation and displaying it not functioning properly?

Why isn't this animation from display none to block working properly? The initial code appears as follows, and it functions correctly: $(".box_outer").stop().animate({top: '25px' , opacity: 1}, 100); When I add display: none; to the class ...

Delaying the intensive rendering process in Vue.js and Vuetify: A comprehensive guide

Recently, while working on a project with Vue.js 2 and Vuetify 2.6, I encountered an issue with heavy form rendering within expansion panels. There seems to be a slight delay in opening the panel section upon clicking the header, which is most likely due t ...

The nodemailer module in Node.js encountered an issue while trying to send an email, resulting

Looking to confirm registration, I want to send an email from my server (kimsufi). To accomplish this, I am utilizing nodemailer which can be found at https://github.com/andris9/Nodemailer Encountering the following error: Error occurred Sendmail exited ...

Troubleshooting problem with transmitting data using the b4j jQuery WebSocket library

I'm seeking guidance on the process of sending data through a custom library that connects to a Java server operating as a WebSocket server. The code I'm using for successful connection is: <script src="https://ajax.googleapis.com/ajax/libs/ ...

Adjust the text size for groupBy and option labels in Material UI Autocomplete without altering the size of the input field

Currently, I am utilizing Material-UI and ReactJS to implement grouped autocomplete functionality. See the code snippet below: import * as React from "react"; import TextField from "@mui/material/TextField"; import Autocomplete from &q ...

What is the best way to add animation to my `<div>` elements when my website is first loaded?

I am looking for a way to enhance the appearance of my <div> contents when my website loads. They should gradually appear one after the other as the website loads. Additionally, the background image should load slowly due to being filtered by the wea ...

Is there a way to sequentially execute requests in a loop?

My goal is to extract a list of URLs from the request body, pass them to a request function (using the request module) to retrieve data from each URL, and then save that data to MongoDB. The response should be sent only after all requests are completed, in ...

Auto Start Feature for jQuery Slider Function

Hey there, I currently have an image slider on my website that allows users to navigate through images by clicking on preview and next buttons. My query is: would it be possible to implement an auto start feature instead of having to click manually? Belo ...

Phonegap app failing to run Ajax request properly

I have recently updated my Android app using phonegap build to the latest version, cli-5.2.0. Here is a snippet of my config: <preference name="phonegap-version" value="cli-5.2.0" /> Additionally, here is how my overall configuration looks like: & ...

Unable to receive comment reply through Ajax without refreshing the comment section

I'm facing an issue where I cannot retrieve comment replies via Ajax under comments, even though the replies are successfully saved in the database. Oddly enough, upon refreshing the Index.php page, the replies display correctly. I suspect the problem ...

Obtain the AngularJS service using Vanilla JavaScript

Trying to access the AngularJS service from plain JavaScript. Utilizing the following syntax: angular.injector(['ng', 'error-handling']).get("messagingService").GetName(); It works fine when the messagingservice has no dependencies. H ...

Utilize MaterialUI Grid to define custom styles for the ::after pseudo-element

I came across a helpful article on Stack Overflow about Flex-box and how to align the last row to the grid. I'm interested in implementing it in my project: .grid::after { content: ""; flex: auto; } However, I'm not sure how to inc ...

Combination of AngularJS and jQuery

I have a page in which additional input fields are dynamically added based on the selection made in a drop-down menu. This page is powered by angularjs, but I had to use jQuery specifically for adding these extra input fields. Here is the HTML code snippe ...

Steps for triggering a click event on a div with a button role within a class containing multiple elements

Can anyone help me figure out how to auto-click every button in Instagram's "hide story from" settings using console? I tried the following code: for (let i = 0; i < 300; i++) { document.getElementsByClassName('wbloks_1')[i] ...

Delay the loading of JavaScript libraries and multiple functions that are only executed once the document is

After learning how to defer the loading of JS libraries and a document ready function from this post, I encountered a challenge. The code I currently have handles multiple document ready functions inserted by different modules, not on every page. echo&ap ...

Kik Card - Using Synchronous XMLHttpRequest within the Kik.js Script

Getting ready to create a mobile web app powered by Kik! First step, insert the Kik.js script at the bottom of your HTML page... <!-- add this script to your webpage --> <script src="http://cdn.kik.com/kik/2.3.6/kik.js"></script> Excel ...

discord.js: Bot keeps sending duplicate embeds

I recently set up my discord bot to respond with a message when I enter a specific command, but I've run into an issue where it's sending the same embed twice. I've tried troubleshooting, but so far I haven't been able to pinpoint the c ...

Searching for a specific value in various Json files: A guide

My goal is to create an application where users can input longitude and latitude coordinates of a location, and the application will return the associated grid code from one of three JSON data files. I am attempting to search through all three files simult ...

Is it true that Javascript does not allow for saving or outputting actions?

After coming across this question, I discovered a way to extract a specific element from a Google translate page using Javascript. However, I also learned that it is nearly impossible to directly save something to the clipboard in Javascript without user i ...