xml tag replace showing different result - javascript

I wrote a function in one of my angular project to replace tag with another tag in xml file. First parameter is the HTMLElement, second parameter is the searchTag and third one is replaceTag.
replaceTagWith(xmlCode: HTMLElement, findTag: string, replaceTag: string) {
// Initializing variables
let exists: boolean = true;
let processed: boolean = false;
while (exists) {
let sourceTags = xmlCode.querySelector(findTag);
// If findTag exists
if (sourceTags) {
// Setting processed flag
processed = true;
// Creating replace tag and setting the textcontent
let targetTag = document.createElement(replaceTag);
targetTag.innerHTML = sourceTags.innerHTML;
// Finding attributes of the tags to be replaced
let tagAttributes = sourceTags.attributes;
let attrLength = tagAttributes.length;
// If there is attributes
if (attrLength) {
for (let j = 0; j < attrLength; j++) {
// Setting the attribute of replace tag
targetTag.setAttribute(tagAttributes[j].name, tagAttributes[j].value);
}
}
// Appending the target tag just before the source tag
sourceTags.parentNode.insertBefore(targetTag, sourceTags);
// Removing findTag
sourceTags.parentNode.removeChild(sourceTags);
} else {
exists = false;
}
}
This function works well when i am replacing <title> tag with <sec-title>. Here is the function call..
const parser = new DOMParser();
const xml = parser.parseFromString(this.xmlData, 'application/xml');
let xmlCode: any = xml.documentElement;
this.replaceTagWith(xmlCode, 'title', 'sec-title');
the result will be like:
<sec-title xmlns="http://www.w3.org/1999/xhtml">What is Child Protection<named-content xmlns="http://www.w3.org/1999/xhtml" content-type="index" name="default" a-level="child protection" b-level="definition of" c-level="" d-level="" e-level="" format="" range="" see="" see-also=""></named-content> in Humanitarian Action? </sec-title>
But the problem is that when i try to replace <sec-title> with <title> ,the result showing:
<title xmlns="http://www.w3.org/1999/xhtml">What is Child Protection<named-content xmlns="http://www.w3.org/1999/xhtml" content-type="index" name="default" a-level="child protection" b-level="definition of" c-level="" d-level="" e-level="" format="" range="" see="" see-also=""></named-content> in Humanitarian Action? </title>
the html tags (here <named-content>) inside the <title> get replaced with <named-content>
This is the portion of xml I am working with..
<sec level="2" id="sec002" sec-type="level-B">
<title xmlns="http://www.w3.org/1999/xhtml">What is Child Protection<named-content content-type="index"
name="default" a-level="child protection" b-level="definition of" c-level="" d-level="" e-level=""
format="" range="" see="" see-also=""></named-content> in Humanitarian Action? </title>
<p specific-use="para">Child protection is the ‘prevention of and response to abuse, neglect, exploitation and
violence against children’.</p>
<p specific-use="para">The objectives of humanitarian action are to:</p>
<list list-type="bullet" specific-use="1" list-content="Lijstalinea">
<list-item>
<p specific-use="para">Save lives, alleviate suffering and maintain human dignity during and after
disasters; and</p>
</list-item>
<list-item>
<p specific-use="para">Strengthen preparedness for any future crises.</p>
</list-item>
</list>
<p specific-use="para">Humanitarian crises<named-content xmlns="http://www.w3.org/1999/xhtml"
content-type="index" name="default" a-level="humanitarian crises" b-level="causes of" c-level=""
d-level="" e-level="" format="" range="" see="" see-also=""></named-content> can be caused by humans,
such as conflict or civil unrest; they can result from disasters, such as floods and earthquakes; or they
can be a combination of both.</p>
<p specific-use="para">Humanitarian crises<named-content xmlns="http://www.w3.org/1999/xhtml"
content-type="index" name="default" a-level="humanitarian crises" b-level="effects on children of"
c-level="" d-level="" e-level="" format="" range="" see="" see-also=""></named-content>
often have long-lasting, devastating effects on children’s lives. The child protection risks children face
include family separation, recruitment into armed forces or groups, physical or sexual abuse, psychosocial
distress or mental disorders, economic exploitation, injury and even death. They depend on factors such as
the:</p>
<list list-type="bullet" specific-use="1" list-content="Lijstalinea">
<list-item>
<p specific-use="para">Nature and scale of the emergency;</p>
</list-item>
<list-item>
<p specific-use="para">Number of children affected;</p>
</list-item>
<list-item>
<p specific-use="para">Sociocultural norms;</p>
</list-item>
<list-item>
<p specific-use="para">Pre-existing child protection risks;</p>
</list-item>
<list-item>
<p specific-use="para">Community-level preparedness; and</p>
</list-item>
<list-item>
<p specific-use="para">Stability and capacity of the State before and during the crisis.</p>
</list-item>
</list>
<p specific-use="para">Child protection actors and interventions seek to prevent and respond to all forms of
abuse, neglect, exploitation and violence. Effective child protection builds on existing capacities and
strengthens preparedness before a crisis occurs. During humanitarian crises, timely interventions support
the physical and emotional health, dignity and well-being of children, families and communities.</p>
<p specific-use="para">Child protection in humanitarian action includes specific activities conducted by local,
national and international child protection actors. It also includes efforts of non-child protection actors
who seek to prevent and address abuse, neglect, exploitation and violence against children in humanitarian
settings, whether through mainstreamed or integrated programming.</p>
<p specific-use="para">Child Protection in Humanitarian Action promotes the well-being and healthy development
of children and saves lives.</p>
</sec>
To display this code in broser i first replaced the <title> tag with <sec-title> and it works fine. Finally at the stage of exporting xml i replaced back <sec-title> with <title>. Here is the stage where the problem occurring...

Related

One div input element will not pull information from sessionStorage using javascript

enter image description hereI am trying to develop a ticketing tool for work and its a template site to make taking notes for helpdesk more easily and when something is an escalation and you click the button for escalation template. When the escalation template loads I want it to pull information from session storage to avoid copying and pasting notes already taken.
This is how I am storing the information in session storage and I checked via Chrome browser that information is being stored in the session storage.
if(callInbound)
{
sessionStorage.setItem("ACTIVITYTYPE", document.form1.activity.value);
sessionStorage.setItem("CONTACTNAME", document.form1.name.value);
sessionStorage.setItem("VIPSTATUS", document.form1.vip.value);
sessionStorage.setItem("CONTACTNUMBER", document.form1.phone.value);
sessionStorage.setItem("CALLERLOCATION", document.form1.location.value);
sessionStorage.setItem("ISSUEDESCRIPTION",document.form1.issueDescription.value); <--PROBLEM ITEM
sessionStorage.setItem("ERRORMESSAGE", document.form1.errorMessage.value);
sessionStorage.setItem("TROUBLESHOOTING", document.form1.troubleshooting.value);
sessionStorage.setItem("KNOWLEDGEUSED", document.form1.knowledgeUsed.value);
sessionStorage.setItem("SEARCHTERMSTRIED", document.form1.searchtermsTried.value);
sessionStorage.setItem("SCREENSHOTSATTACHED", document.form1.screenshotsAttached.value);
sessionStorage.setItem("SURVEYOFFERED", document.form1.surveyOffered.value);
sessionStorage.setItem("SURVEYTAKEN", document.form1.surveyTaken.value);
}
This is the page where the information is being loaded and all but the one identified as problem is being populated into the template.
<!DOCTYPE html>
<html><head><meta http-equiv="Content-Type" content="text/html; charset=windows-1252"><title>DSI Call Outbound</title>
<script type="text/javascript" src="DSI.js"></script>
<script language="JavaScript" type="text/javascript">
window.addEventListener('load', ()=>{
let callInboundCallDropped = sessionStorage.getItem("CALLINBOUNDCALLDROPPED");
let callOutboundCallDropped = sessionStorage.getItem("CALLOUTBOUNDCALLDROPPED")
let additionalIssue = sessionStorage.getItem("ADDITIONALISSUE");
let voicemailCallBack = sessionStorage.getItem("VOICEMAILRECEIVED");
if (callInboundCallDropped == "true")
{
document.form1.issueDescription.value = sessionStorage.getItem("ISSUEDESCRIPTION");<--Problem Item
document.form1.name.value = sessionStorage.getItem("CONTACTNAME");
document.form1.phone.value = sessionStorage.getItem("CONTACTNUMBER");
document.form1.errorMessage.value = sessionStorage.getItem("ERRORMESSAGE");
}
else if (callOutboundCallDropped == "true")
{
document.form1.name.value = sessionStorage.getItem("CONTACTNAME");
document.form1.phone.value = sessionStorage.getItem("CONTACTNUMBER");
document.form1.issueDescription.value = sessionStorage.getItem("ISSUEDESCRIPTION");<--Problem item
document.form1.errorMessage.value = sessionStorage.getItem("ERRORSMESSAGE");
}
else if(additionalIssue == "true")
{
document.form1.activity.value = "***ADDITIONAL ISSUE***";
document.form1.name.value = sessionStorage.getItem("CONTACTNAME");
document.form1.phone.value = sessionStorage.getItem("CONTACTNUMBER");
}
else if(voicemailCallBack == "true");
{
document.form1.name.value = sessionStorage.getItem("CONTACTNAME");
document.form1.phone.value = sessionStorage.getItem("CONTACTNUMBER");
document.form1.issueDescription.value = sessionStorage.getItem("VOICEMAILSUBJECT");
document.form1.errorMessage.value = sessionStorage.getItem("ERRORMESSAGE");
}
//sessionStorage.clear();
})
</script>
All other items load properly from session storage when the page is loaded. I confirmed that the information is in session storage via the application section in the inspection section of Chrome browser and by adding alert("ISSUEDESCRIPTION"); below the problem item line and it works as expected.
I have tried the following:
// Store your value from one page sessionStorage.setItem("values",
"input_text");
// Retrieve the value from another page var value =
sessionStorage.getItem("values");
//replacing the line with and assigning and id to the div element in the html document.getElementById("issueDescription").value = sessionStorage.getItem("ISSUEDESCRIPTION");
This is the problem element:
<div class="w3-row w3-section">
<div class="w3-col" style="width:50px"><i class="w3-xxlarge w3-animate-zoom"></i></div>
<div class="w3-rest">
<p>Issue Description</p>
<input class="w3-input w3-border" name="issueDescription" type="text" placeholder="[Issue Description Here]">
</div>
</div>
This is an element on the same page that is correctly being filled with session storage information:
<div class="w3-row w3-section">
<div class="w3-col" style="width:50px"><i class="w3-xxlarge w3-animate-zoom"></i></div>
<div class="w3-rest">
<p>Phone Number Used</p>
<input class="w3-input w3-border" name="phone" type="text" placeholder="(xxx)xxx-xxxx">
</div>
</div>
please tell me if I'm just referencing something incorrectly like a typo although I've spent multiple hours doublechecking everything. Wish there were a troubleshooting/debugging feature in Visual Studio Code for this kind of stuff to step through it. If there is and I'm unaware please let me know.
Unsure of why this didn't work the first few times I tried it, but this time when I copied and pasted the elements name in the "documents.form1.issueDescription.value = sessionStorage.getItem("ISSUEDESCRIPTION");"
the issue was resolved, swear I did this on repeat late last night, must've been a spelling error.

Execute JS using Python and store results in an array

I am working on this website where there is an SVG map and radio buttons as filters :
To get the result of the filter in the map (countries colored in blue), I execute this javascript snippet :
var n = $("input[name=adoptionStatus]:checked").val();
(n == undefined || n === "") && (n = "00000000000000000000000000000000");
$(".status-text").hide();
$("#" + n).show();
$("#vmap").vectorMap("set", "colors", resetColorsData);
resetColorsData = {};
colorsData = {};
$("#countries_list a").each(function(t, i) {
$(i).data("adoption-status").indexOf(n) >= 0 && (colorsData[$(i).data("country-code")] = "#2f98cb", resetColorsData[$(i).data("country-codecountry-code")] = "#fefefe")
});
$("#vmap").vectorMap("set", "colors", colorsData)
The variable n is used to store the value of the radio button like in this case cae64c6b731d47cca7565b2a74d11d53 :
<div class="map-filter-radio radio">
<label>
<input type="radio" name="adoptionStatus" alt="IFRS Standards are permitted, but not required, for use by at least some domestic publicly accountable entities, including listed companies and financial institutions." title="IFRS Standards are permitted, but not required, for use by at least some domestic publicly accountable entities, including listed companies and financial institutions." value="cae64c6b731d47cca7565b2a74d11d53">
IFRS Standards are permitted but not required for domestic public companies
</label>
</div>
When I execute the Javascript in the console and try to get the colorsData, I get the list of the countries colored in blue like below :
bm: "#2f98cb"
ch: "#2f98cb"
gt: "#2f98cb"
iq: "#2f98cb"
jp: "#2f98cb"
ky: "#2f98cb"
mg: "#2f98cb"
ni: "#2f98cb"
pa: "#2f98cb"
py: "#2f98cb"
sr: "#2f98cb"
tl: "#2f98cb"
How can I execute the JS script on the webpage and get the result of the colored countries in an array using python ?
By looking at the list of countries specified by #countries_list, you got a list of a tag like the following :
<a id="country_bd" data-country-code="bd" data-adoption-status="97f9b22998d546f7856bb1b4f0586521|3adc18f07ff64c908a6d835e08344531|ff784361818644798ea899f81b8b6d61" href="/use-around-the-world/use-of-ifrs-standards-by-jurisdiction/bangladesh/">
<img src="/-/media/7bfd06a698594c2cb3614578a41caa9e.ashx" alt="Bangladesh">
Bangladesh
</a>
The data-adoption-status attribute is a list of adoptionStatus delimited by |.
You just need to split them and match only the countries that reference the value from the input adoptionValue like this :
if selectedAdoptionStatus in t["data-adoption-status"].split("|")
The following code lists all input tag and extracts the adoptionStatus for each one of these, it prompts user to choose a filter (0 to 4) and gets the selected countries by filtering on the data-adoption-status attribute :
import requests
from bs4 import BeautifulSoup
r = requests.get("https://www.ifrs.org/use-around-the-world/use-of-ifrs-standards-by-jurisdiction/")
soup = BeautifulSoup(r.text, "html.parser")
choiceContainer = soup.find("div", {"class":"map-filters"})
choices = [
(t["title"], t["value"])
for t in choiceContainer.findAll("input")
]
for idx, choice in enumerate(choices):
print(f"[{idx}] {choice[0]}")
val = input("Choose a filter index : ")
choice = choices[int(val)]
print(f"You have chosen {choice[0]}")
selectedAdoptionStatus = choice[1]
countryList = soup.find("div", {"id":"countries_list"})
selectedCountries = [
{
"countryCode": t["data-country-code"],
"adoptionStatus": t["data-adoption-status"].split("|"),
"link": t["href"],
"country": t.find("img")["alt"]
}
for t in countryList.findAll("a")
if selectedAdoptionStatus in t["data-adoption-status"].split("|")
]
for it in selectedCountries:
print(it["country"])
run this code on repl.it
Sample output
[0] IFRS Standards are required for use by all or most domestic publicly accountable entities.
[1] IFRS Standards are permitted, but not required, for use by at least some domestic publicly accountable entities, including listed companies and financial institutions.
[2] IFRS Standards are required or permitted for use by foreign securities issuers.
[3] In most cases an SME may also choose full IFRS Standards. In some cases, an SME may also choose local standards for SMEs.
[4] The body with authority to adopt financial reporting standards is actively studying whether to adopt the <em>IFRS for SMEs</em> Standard.
Choose a filter index : 1
You have chosen IFRS Standards are permitted, but not required, for use by at least some domestic publicly accountable entities, including listed companies and financial institutions.
Bermuda
Cayman Islands
Guatemala
Iraq
Japan
Madagascar
Nicaragua
Panama
Paraguay
Suriname
Switzerland
Timor-Leste

Sending data through Components

I am having this problem which I can not solve. So basically I have 2 components here Component A and Component G I have more of them but they are pretty much the same(concept is the same). I have a Link in Component G, A which when I click it, it brings me to the Payment Component. Tt now renders the (ImageA, ClassA and PriceA) its hard coded. Anyway what I am trying to achieve is that when I click for example on the Component G it renders only that (imageG, classG and priceG), so I would need it to filter it somehow or split the data somehow in the json file I imagine, but I dont know how to do it. I hope one of you fellow comrades will help me.
Payment Component
const Payment = ({
history,
location: { state },
match: {
params: { dataId }
}
}) => {
if (!state?.postData) {
history.goBack();
}
const { postData } = state;
return (
<div className="ml-20">
<img
alt=""
className="w:2/4 object-contain "
src={postData.imageG}
/>
<h2
className=" ml-24 mlg:ml-6 mlg:mt-2 mlg:static text-5xl mlg:text-2xl text-blue-400 absolute top-
48" >
{postData.classG}
</h2>
<h3
className="text-lg mlg:mb-2 mlg:ml-6 mlg:mt-2 mlg:static font-bold text-green-800
font-mono ml-24 top-64 absolute"
>
{postData.priceG}
</h3>
</div>
);
};
export default Payment
A COMPONENT
import React from "react";
import data from "../data.json";
import { Link } from "react-router-dom";
function A() {
return (
<div className='bg-black '>
{data.filter(d =>
d.classA &&
d.imageA &&
d.priceA)
.map((postData) => {
return (
<div className='bg-black' key={postData.id} >
<div className='bg-black '>
<img
alt=""
className="w-full object-contain "
src={postData.imageA}
></img>
<h1 className=" ml-24 mlg:ml-6 mlg:mt-2 mlg:static text-5xl mlg:text-2xl text-red-600
absolute top-48">
{postData.classA}
</h1>
<h1 className="text-lg mlg:mb-2 mlg:ml-6 mlg:mt-2 mlg:static font-bold text-yellow-600
font-mono ml-24 top-64 absolute" >
{postData.priceA}
</h1>
<Link
to={{pathname: `/payment/${postData.id}`,
state: {
postData,
},
}}
className="py-1 px-2 mlg:ml-6 mlg:mt-14 mlg:static text-black-600 h-8 ml-24 top-72 bg-
white w-32 text-center text-gray-red
rounded-full focus:outline-none focus:ring-2 focus:ring-gray-600 absolute"
>
Buy Now
</Link>
</div>
</div>
</div>
)
}
export default A
G Component
import React from "react";
import data from "../data.json";
import { Link } from "react-router-dom";
function G() {
return (
<div className='bg-black '>
{data.filter(d =>
d.classG &&
d.imageG &&
d.priceG)
.map((postData) => {
return (
<div className='bg-black' key={postData.id} >
<div className='bg-black '>
<img
alt=""
className="w-full object-contain "
src={postData.imageG}
></img>
<h1 className=" ml-24 mlg:ml-6 mlg:mt-2 mlg:static text-5xl mlg:text-2xl text-red-600
absolute top-48">
{postData.classG}
</h1>
<h1 className="text-lg mlg:mb-2 mlg:ml-6 mlg:mt-2 mlg:static font-bold text-yellow-600
font-mono ml-24 top-64 absolute" >
{postData.priceG}
</h1>
<Link
to={{pathname: `/payment/${postData.id}`,
state: {
postData,
},
}}
className="py-1 px-2 mlg:ml-6 mlg:mt-14 mlg:static text-black-600 h-8 ml-24 top-72 bg-
white w-32 text-center text-gray-red
rounded-full focus:outline-none focus:ring-2 focus:ring-gray-600 absolute"
>
Buy Now
</Link>
</div>
</div>
</div>
)
}
export default G
Json file
[
{
"id":0,
"classG":"G-Class",
"imageG":"./ModImages/Gclass.jpg",
"priceG":"Starting at $154,900",
"newG":"A 12.3-inch digital gauge cluster is newly standard across the
board, as are heated front seats. Plus, the sedan can be had with a Night
package that adds black exterior trim.",
"imageGIn":"./ModImages/GclassIn.jpg",
"imageCOut":"./ModImages/GclassOut.jpg",
"infoDesignC1":"How many technological breakthroughs can you fit into a C-
Class? With the advanced, powerful and sporty 2020 C 300 Wagon, plenty. From
its LED headlamps to its generous cargo hold, you'll find countless
refinements, and so many reasons it's a wagon like no other.",
"infoDesignG" :"The acclaimed C-Class cabin is as functional as it is
beautiful. Abundant innovations harmonize with five options in hand-finished
wood trim. A 12.3-inch digital instrument cluster and 10.25-inch centre
screen are available.",
"imageGIn1":"./ModImages/CclassIn1.jpg",
"imageGOut1":"./ModImages/CclassOut1.jpg",
"infoDesign2": "The Star on the outside is earned on the inside. The roomy,
refined cabin includes heated front seats and a driver-seat memory. Dual-
zone, double-filtered climate control. A panoramic sunroof. And options from
Burmester® surround sound to new Climate Comfort front seats.",
"infoInov": "Available Apple CarPlay™ and Android Auto let you enjoy more
from your own smartphone. Another navigation option is COMAND, which brings
you voice control not only for navigation and audio, but also many cabin
features.",
"imageInov1":"./ModImages/GclassInov1.jpg",
"imageInov2":"./ModImages/GclassInov2.jpg",
"infoInov1": "Available wireless charging lets you refuel your compatible
phone's battery as you drive. Easy-connect NFC pairing links your phone
every
time you get in. Apple CarPlay™ and Android Auto are available, too. And
four USB-C ports are standard.",
"infoInov2": "DYNAMIC SELECT lets you fine-tune your A-Class with the tap of
a console button. Four modes vary shift points, throttle response, steering
feel and more: efficient ECO, everyday Comfort, sharpened Sport, and create-
your-own Individual.",
"imageInov":"./ModImages/GclassInov.jpg",
"imageInov4":"./ModImages/GclassInov4.jpg" ,
"infoInov4G": "From the everyday to the unexpected, Mercedes me connect helps
ease your way. You can control vehicle features from your smartphone
(including Remote Start), set up a service appointment, and more. You can
also add In-car Wi-Fi for a low monthly rate. ",
"infoInov5C":"Available driver assists help de-stress driving, changing lanes
with a tap of your finger, and knowing to slow for a tollboth or exit. A
network of sensors keeps a constant lookout for danger ahead, even if it's
coming from behind."
},
{
"id":1,
"classA":"A-Class",
"imageA":"./ModImages/Aclass.jpg",
"priceA":"Starting at $54,900",
"newA":"In addition to a new 18-inch wheel design, the 2021 A-class gains
standard blind-spot monitoring and an optional gesture control feature for
the MBUX infotainment system.",
"imageAIn":"./ModImages/AclassIn.jpg",
"imageAOut":"./ModImages/AclassOut.jpg",
"infoDesignA":"A is for attention-getting. The clean lines, LED lighting and
aggressive stance of the A-Class Sedan are designed to capture admiring eyes.
Its ultramodern cabin and premium appointments aim to captivate its driver
and passengers for years to come.",
"infoDesignA1" :"With 100% LED lighting standard, inside and out, the A-Class
shines day or night, coming or going, and staying, too. Options include
MULTIBEAM LED headlamps and 64-colour ambient cabin lighting.",
"imageAIn1":"./ModImages/AclassIn1.jpg",
"imageAOut1":"./ModImages/AclassOut1.jpg",
"infoDesignA2": "The Star on the outside is earned on the inside. The roomy,
refined cabin includes heated front seats and a driver-seat memory. Dual-
zone, double-filtered climate control. A panoramic sunroof. And options from
Burmester® surround sound to new Climate Comfort front seats.",
"infoInov": "A is for advanced. With the Mercedes-Benz User Experience
(MBUX), the A-Class drives a new generation of user-friendly tech. Quite
possibly the most capable, natural and intuitive speech interface from any
automaker, it's easy to learn because it learns you.",
"imageInov1":"./ModImages/AclassInov1.jpg",
"imageInov2":"./ModImages/AclassInov2.jpg",
"infoInov1": "Available wireless charging lets you refuel your compatible
phone's battery as you drive. Easy-connect NFC pairing links your phone
every time you get in. Apple CarPlay™ and Android Auto are available, too.
And four USB-C ports are standard. Disclaimer[6] Disclaimer",
"infoInov2": "DYNAMIC SELECT lets you fine-tune your A-Class with the tap of
a console button. Four modes vary shift points, throttle response, steering
feel and more: efficient ECO, everyday Comfort, sharpened Sport, and create-
your-own Individual.",
"imageInov3":"./ModImages/AclassInov3.jpg",
"imageInov4":"./ModImages/AclassInov4.jpg" ,
"infoInov4": "Get up close with the A-Class Sedan in this captivating ASMR audio experience. "
}
]
I'm updating the answer based on the comments
First thing, I would make sure my JSON properties are consistent across objects:
[
{
"id":0,
"class":"G-Class",
"image":"./ModImages/Gclass.jpg",
"price":"Starting at $154,900",
"new":"Mercedes-Benz introduces a mid-cycle update of the E-class lineup for 2021. The changes
apply",
"infoInov": "....",
"imageOut": "..."
},
{
"id":1,
"class":"A-Class",
"image":"./ModImages/Aclass.jpg",
"price":"Starting at $54,900",
"new":"Mercedes-Benz introduces a mid-cycle update of the E-class lineup for 2021. The changes
apply",
"infoInov": "....",
"imageOut": "..."
}
]
Since all the properties are consistent, the only way you can consistently tell them apart is by the id property. If id === 0, we know it's the G. if === 1, we know it's A, and so on.
This way, I can use only one component to render them both. If you want to apply different styles or render something if it's component G, you can do something like:
function AG() {
return (
<div className="bg-black">
{data.map(product => (
<div>
<img src={product.image} />
<h1>{product.class}</h1>
<h1 className={product.id === 0 ? 'g-class' : ''}>{product.price}</h1>
<Link to={`/payment/${product.id}` />
{product.id === 0 && <div>This will only appear to G</div>}
</div>
))}
</div>
)
}
Notice above that I have some checks to apply styles or render something only if product.id === 0. This is one of the ways to reuse a component and apply little changes to it.
In the <Link> we are sending the user to /payments passing the productID in the path. So inside the Payments component, you would use this productID to filter the data from the JSON.
Now in the Payment component, you can just import the same JSON data and filter by the id we are passing in the URL path:
import data from "../data.json"
const Payment = () => {
// get the id from the URL somehow, I suppose you are using react router
// this is just an example
const { idFromURL } = match.param
const filteredProduct = data.filter(product => product.id === idFromURL)
return (
<div>
<img src={filteredProduct.image} />
</div>
)
}
Now the filteredProduct variable has the data for either A or G, and you can use it to display the specific data you want, inside the Payment component.

How to parse an XML object in Javscript

This is probably a relatively simple problem but I am finding it difficult to be able to parse my specific xml object in javascript.
My XML looks like this
<ns2:GetItemResponse xmlns:ns2="urn:ebay:apis:eBLBaseComponents">
<Ack>Success</Ack>
<Build>E1125_INTL_API_19070421_R1</Build>
<Item>
<AutoPay>false</AutoPay>
<BuyItNowPrice>0.0</BuyItNowPrice>
<BuyerProtection>ItemIneligible</BuyerProtection>
<Charity>
<CharityID>1135</CharityID>
<CharityName>The Humane Society of the United States</CharityName>
<CharityNumber>1726</CharityNumber>
<DonationPercent>10.0</DonationPercent>
<LogoURL>https://i.ebayimg.com/00/s/NzYyWDEzNzM=/z/K3EAAOSwFgNdVeRz/$_1.JPG?set_id=8800005007
</LogoURL>
<Mission>
The Humane Society of the United States is the nation's most effective animal protection organization. Since 1954, HSUS has been fighting for the protection of all animals through advocacy, education and hands-on programs. Together with our affiliates, we rescue and care for tens of thousands of animals each year, but our primary mission is to prevent cruelty before it occurs. We're there for all animals!
</Mission>
<Status>Valid</Status>
</Charity>
<Country>US</Country>
<Description>
<p dir="ltr">Wolverine #100 - April 1996 Marvel Comics The 100th Issue! Comic Book. </p>
</Description>
</Item>
<Timestamp>2020-02-13T14:19:33.939Z</Timestamp>
<Version>1125</Version>
</ns2:GetItemResponse>
I basically want to display the Item properties and Charity properties but I am finding it difficult to understand the child nodes of these objects I have tried doing this
parser = new DOMParser();
var obj = request.responseXML;
console.log(obj.getElementsByTagName("Item")[0]);
xmlDoc = parser.parseFromString(request.responseText, "text/xml");
// panel.innerHTML += "<br> " + xmlDoc.getElementsByTagName("ItemId")[0].childNodes[0].nodeValue ;
//console.log(xmlDoc.getElementsByTagName("Timestamp")[0].childNodes[0].nodeValue);
console.log(xmlDoc.getElementsByTagName("Item")[0].childNodes);
All help would be greatly appreciated
simple...
const docXML = `
<ns2:GetItemResponse xmlns:ns2="urn:ebay:apis:eBLBaseComponents">
<Ack>Success</Ack>
<Build>E1125_INTL_API_19070421_R1</Build>
<Item>
<AutoPay>false</AutoPay>
<BuyItNowPrice>0.0</BuyItNowPrice>
<BuyerProtection>ItemIneligible</BuyerProtection>
<Charity>
<CharityID>1135</CharityID>
<CharityName>The Humane Society of the United States</CharityName>
<CharityNumber>1726</CharityNumber>
<DonationPercent>10.0</DonationPercent>
<LogoURL>https://i.ebayimg.com/00/s/NzYyWDEzNzM=/z/K3EAAOSwFgNdVeRz/$_1.JPG?set_id=8800005007
</LogoURL>
<Mission>
The Humane Society of the United States is the nation's most effective animal protection organization. Since 1954, HSUS has been fighting for the protection of all animals through advocacy, education and hands-on programs. Together with our affiliates, we rescue and care for tens of thousands of animals each year, but our primary mission is to prevent cruelty before it occurs. We're there for all animals!
</Mission>
<Status>Valid</Status>
</Charity>
<Country>US</Country>
<Description>
<p dir="ltr">Wolverine #100 - April 1996 Marvel Comics The 100th Issue! Comic Book. </p>
</Description>
</Item>
<Timestamp>2020-02-13T14:19:33.939Z</Timestamp>
<Version>1125</Version>
</ns2:GetItemResponse>`;
const parser = new DOMParser()
, xmlDoc = parser.parseFromString(docXML, "text/xml");
console.log( '1st CharityName = ', xmlDoc.querySelector('Item CharityName').textContent )
.as-console-wrapper { max-height: 100% !important; top: 0; }

Salesforce Lightning Component will not update records via Apex call, freezes

Issue overview: Currently coding a Lightning Component to update records on a custom object. However, every time I trigger the update (via a ui:button), the page freezes and I don't see any errors in the debugger or console. Cannot for the life of me figure out why it won't work.
Context: The component has a number of dropdowns that are populated with records (with the label being the record name). Selecting a new value in the dropdown and hitting "Update" calls the below apex to change a custom field (Status__c = 'Ready') on the new selected item, and then updates the records that occur before it (Status__c = 'Complete). I do all of my security and update checks in another function during init, so you won't see that here (I can post the full code if needed). Just trying to get the update to work.
I would be eternally grateful if someone could show me the error of my ways :]. Always been a huge fan of stackoverflow and looking forward to contributing now that I finally signed up. Thanks for your time everyone!
Apex:
#AuraEnabled
public static void updateMilestones(String deployId,Boolean prodChanged,String newProdMile) {
if( prodChanged == true && newProdMile != null ) {
try {
decimal newProdStepNum;
List <Milestone__c> newReadyProdMile = New List<Milestone__c>();
for(Milestone__c mil1:[SELECT id, Status__c, Step_Order__c FROM Milestone__c
WHERE Deployment__c = :deployID
AND id = :newProdMile LIMIT 1]){
mil1.Status__c = 'Ready';
newProdStepNum = mil1.Step_Order__c;
newReadyProdMile.add(mil1);
}
List <Milestone__c> prodMilesComplete = New List<Milestone__c>();
for(Milestone__c mil2:[SELECT id, Type__C, Status__c FROM Milestone__c
WHERE Deployment__c = :deployID
AND Step_Order__c < :newProdStepNum
AND Type__c = 'Production'
AND Status__c != 'Complete'
AND Status__c != 'Revised']){
mil2.Status__c = 'Complete';
prodMilesComplete.add(mil2);
}
update newReadyProdMile;
update prodMilesComplete;
}
catch (DmlException e) {
throw new AuraHandledException('Sorry, the update did not work this time. Refresh and try again please!');
}
}
}
Javascript:
updateMilestones : function(component, event, helper) {
// update milestones server-side
var action = component.get("c.updateMilestones");
action.setParams({
deployId : component.get("v.recordId"),
newProdMile : component.find("prod-mile-select").get("v.value"),
prodChanged : component.get("v.prodChanged")
});
// Add callback behavior for when response is received
action.setCallback(this, function(response) {
var state = response.getState();
if (component.isValid() && state === "SUCCESS") {
// re-run the init function to refresh the data in the component
helper.milesInit(component);
// refresh record detail
$A.get("e.force:refreshView").fire();
// set Update Changed Milestones button back to disabled
component.find("updateButton").set("v.disabled","true");
// show success notification
var toastEvent = $A.get("e.force:showToast");
toastEvent.setParams({
"title": "Success!",
"message": "Milestones have been updated successfully."
});
toastEvent.fire();
}
});
// Send action off to be executed
$A.enqueueAction(action);
}
Component:
<aura:component controller="auraMilestonesController_v2"
implements="force:appHostable,flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickAction">
<ltng:require scripts="{!$Resource.lodash}" afterScriptsLoaded="{!c.doInit}"/>
<aura:attribute name="recordId" type="String" />
<aura:attribute name="prodMiles" type="Milestone__c[]"/>
<aura:attribute name="prodChanged" type="Boolean" default="false"/>
<!-- FORM -->
<div class="slds-col slds-col--padded slds-p-top--large" id="theform">
<form class="slds-form--stacked">
<!-- UPDATE BUTTON -->
<div class="slds-form-element">
<ui:button aura:id="updateButton" label="Update Changed Milestones" press="{!c.updateMilestones}"
class="slds-button slds-button--brand slds-align--absolute-center" disabled="true"/>
</div>
<hr style="color: #005fb2;background-color: #005fb2;"/>
<!-- PRODUCTION -->
<div aura:id="prod-section">
<div class="slds-form-element">
<label class="slds-form-element__label" for="milestone">Production Milestone</label>
<div class="slds-form-element__control">
<div class="slds-select_container">
<ui:inputSelect aura:id="prod-mile-select" class="slds-select" change="{!c.prodChange}">
<option value="" >--Select One--</option>
<aura:iteration items="{!v.prodMiles}" var="m">
<aura:if isTrue="{!m.Status__c == 'Ready'}">
<option value="{!m.id}" selected="true">{!m.Name} ({!m.User_Name__c})</option>
</aura:if>
<aura:if isTrue="{!m.Status__c == 'Not Ready'}">
<option value="{!m.id}">{!m.Name} ({!m.User_Name__c})</option>
</aura:if>
</aura:iteration>
<option value="completeProdMile" id="completeProdMile">All Production Milestones Complete</option>
</ui:inputSelect>
</div>
</div>
</div>
<div class="slds-form-element">
<label class="slds-form-element__label" for="description">Description</label>
<div class="slds-textarea">
<aura:iteration items="{!v.prodMiles}" var="m">
<aura:if isTrue="{!m.Status__c == 'Ready'}">{!m.Description__c}</aura:if>
<!-- <aura:set attribute="else">All production milestones have been completed.</aura:set> -->
</aura:iteration>
</div>
<hr style="color: #005fb2;background-color: #005fb2;"/>
</div>
</div>
<!-- END PRODUCTION -->
</form>
</div>
<!-- / FORM -->
</aura:component>
I believe the issue is that you have fallen into the all too common trap of naming both a client side and a server side controller method the same (updateMilestones in this case). Try changing the name of either to make them unique and I expect that will get you running.
Yes, there is a bug on this and many of us have been making a very loud noise about getting it fixed!
Also we have a very active Salesforce specific Stack Exchange forum over here https://salesforce.stackexchange.com/ that will get more attention - especially if you tag your posts with lightning-components (e.g. I have my account configured to send me an email alert on every post tagged with lightning-components, locker-service, etc).
That might be javascript causing the error.As it's difficult to solve without knowing the error, I would suggest you debug the error.
Turn on debug mode.
a. From Setup, click Develop > Lightning Components.
b. Select the Enable Debug Mode checkbox.
c. Click Save.
In Chrome Developer Tools, check the "Pause on Caught Exceptions" checkbox in the Sources tab. This can often help finding the source of an issue. Other browsers may have similar options.
Add a debugger statement if you want to step through some code.
debugger;
This is useful when you have a rough idea where the problem might be happening.
debugger
https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/debug_intro.htm

Categories