Find xml attribute values in a SOAP response with javascript - javascript

I'm working on an outlook web add-in, I use GetItem to get the ChangeKey from the Exchange Web Service SOAP response, a value I need to compose further requests. The problem is that so far I haven't been able to get that. I have followed Find xml attribute values with javascript without success.
I'm not sure I'm able to use other external libraries since this is hosted in an office365 environment.
This is what I have been trying to do
var responseXML =
'<?xml version="1.0" encoding="utf-8"?>'+
' <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">'+
' <s:Header>'+
' <h:ServerVersionInfo MajorVersion="15" MinorVersion="20" MajorBuildNumber="3955" MinorBuildNumber="27" Version="V2018_01_08" xmlns:h="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>'+
' </s:Header>'+
' <s:Body>'+
' <m:GetItemResponse xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">'+
' <m:ResponseMessages>'+
' <m:GetItemResponseMessage ResponseClass="Success">'+
' <m:ResponseCode>NoError</m:ResponseCode>'+
' <m:Items>'+
' <t:Message>'+
' <t:ItemId Id="AAMkADZh" ChangeKey="CQABA"/>'+
' <t:Subject>the email subject</t:Subject>'+
' </t:Message>'+
' </m:Items>'+
' </m:GetItemResponseMessage>'+
' </m:ResponseMessages>'+
' </m:GetItemResponse>'+
' </s:Body>'+
'</s:Envelope>';
xmlDoc = $.parseXML(responseXML),
$xml = $(xmlDoc),
$itemId = $xml.find("ItemId");
$itemId.each(function(index, element) {
if(element.attributes["ChangeKey"]) {
console.log("ChangeKey :" + element.attributes["ChangeKey"].value);
}
});
but $itemId does not return a collection, although I'm expecting only one item, i think it doesn't hurt to leave the iteration prepared.
https://jsbin.com/matagujeye/1/edit?js,console

I found out here that I should include the name space and double escape the colons.
So the following code works:
var responseXML =
'<?xml version="1.0" encoding="utf-8"?>'+
' <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">'+
' <s:Header>'+
' <h:ServerVersionInfo MajorVersion="15" MinorVersion="20" MajorBuildNumber="3955" MinorBuildNumber="27" Version="V2018_01_08" xmlns:h="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>'+
' </s:Header>'+
' <s:Body>'+
' <m:GetItemResponse xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">'+
' <m:ResponseMessages>'+
' <m:GetItemResponseMessage ResponseClass="Success">'+
' <m:ResponseCode>NoError</m:ResponseCode>'+
' <m:Items>'+
' <t:Message>'+
' <t:ItemId Id="AAMkADZh" ChangeKey="CQABA"/>'+
' <t:Subject>the email subject</t:Subject>'+
' </t:Message>'+
' </m:Items>'+
' </m:GetItemResponseMessage>'+
' </m:ResponseMessages>'+
' </m:GetItemResponse>'+
' </s:Body>'+
'</s:Envelope>';
xmlDoc = $.parseXML(responseXML),
$xml = $(xmlDoc),
$itemId = $xml.find("t\\:ItemId");
$itemId.each(function(index, element) {
if(element.attributes["ChangeKey"]) {
console.log("ChangeKey :" + element.attributes["ChangeKey"].value);
}
});

Related

Dojo - request.post on button click - syntax error

Three questions:
1) Is there any way to make this code more neater? Mainly to avoid so much nesting and quotes within quotes issues?
2) Any advice on parsing error below. I tested some code separately to mke sure it works. (see second code box below).
3) I'm getting "undefined" when I look at request.body in the NodeJS server program that handles this request. From what I read, I didn't need a body parser if the content-type was set to application/json.
<button id="updateStudentButton" data-dojo-type="dijit/form/Button"
data-dojo-props="iconClass:'dijitIconTask',
onClick:function(){
var url = '../student/' + dom.byId('studentId').value;
var studId = dojo.byId('studentId').value;
dom.byId('studentFeedback').value +=
'updateStudentButton clicked studentID=' + studId + '\n';
var firstname = dom.byId('studentFirstname').value;
var lastname = dom.byId('studentLastname').value;
var postBody = JSON.parse(
'{ \"data\": {' +
' \"firstname\": "' + firstname + '\",' +
' \"lastname\": "'+ lastname + '\"' +
'},' +
'\"headers\": { ' +
' \"Content-Type\": \"application/json\" ' +
'}}'
);
dom.byId('studentFeedback').value += 'postBody=' + postBody + '\n';
require(['dojo/request'], function(request){
// AJAX Post the data to the server
request.post(url, postBody
).then(function(response){
dom.byId('studentFeedback').value += response + '\n';
// parse and return data in text boxes
var respJSON = JSON.parse(response);
var rowsAffected = respJSON.rowsAffected;
dom.byId('studentFeedback').value += 'rowsAffected=' + rowsAffected + '\n';
},
function(error){
dom.byId('studentFeedback').value += response;
});
})
}
">
Update
</button>
I tested separatley in NodeJS to make sure quotes all work and saw the correct console.log:
var firstname = 'John';
var lastname = 'Doe';
var postBody = JSON.parse(
'{ \"data\": {' +
' \"firstname\": "' + firstname + '\",' +
' \"lastname\": "'+ lastname + '\"' +
'},' +
'\"headers\": { ' +
' \"Content-Type\": \"application/json\" ' +
'}}'
);
console.log ("postBody=");
console.dir (postBody);
Getting parsing error:
dojo/parser::parse() error Error: SyntaxError: Invalid or unexpected token in data-dojo-props='iconClass:'dijitIconTask',
onClick:function(){
var url = '../student/' + dom.byId('studentId').value;
var firstname = dom.byId('studentFirstname').value;
var lastname = dom.byId('studentLastname').value;
var postBody = JSON.parse(
'{ \'
at Object.construct (parser.js.uncompressed.js:401)
at Object.<anonymous> (parser.js.uncompressed.js:190)
at Object.map (dojo.js:8)
at Object._instantiate (parser.js.uncompressed.js:184)
at parser.js.uncompressed.js:893
at _2f8 (dojo.js:8)
at Promise.then._305.then (dojo.js:8)
at Object.parse (parser.js.uncompressed.js:890)
at Object._parse (html.js.uncompressed.js:301)
at Object.onEnd (html.js.uncompressed
The way to avoid quotes within quotes issue is to have your onClick javascript code inside <script></script> tags.
Below a modified version of your code that works Ok in my environment. The request activates the error callback as I don't have the server handling side.
See the documentation here for the declarative details (use of data-dojo-event), and here for the request details.
For the request, I have stringified the data, as this is what I do in my application (php on the server side). The documentation says it can be a string or object, you may want to try sending the data object, depending on what your server environment expects.
Rgds,
jc
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Neal Walters stask overflow test</title>
<link rel="stylesheet" href="dojo-release-1.12.2-src/dijit/themes/claro/claro.css" media="screen">
</head>
<body class="claro">
<button type="button" id="updateStudentButton" data-dojo-type="dijit/form/Button" data-dojo-props="iconClass:'dijitIconTask'">
<span>update</span>
<script type='dojo/on' data-dojo-event='click'>
var dom = require('dojo/dom');
var url = '../student/' + dom.byId('studentId').value;
var studId = dom.byId('studentId').value;
dom.byId('studentFeedback').value += 'updateStudentButton clicked studentID=' + studId + '\n';
var firstname = dom.byId('studentFirstname').value;
var lastname = dom.byId('studentLastname').value;
var data = {firstname: firstname, lastname: lastname};
//dom.byId('studentFeedback').value += 'postBody=' + postBody + '\n';
require(['dojo/request'], function(request){
// AJAX Post the data to the server
request.post(url, {data: JSON.stringify(data), method: 'POST', handleAs: 'json'}).then(
function(response){
dom.byId('studentFeedback').value += JSON.stringify(response) + '\n';
// parse and return data in text boxes
var rowsAffected = response.rowsAffected;
dom.byId('studentFeedback').value += 'rowsAffected=' + rowsAffected + '\n';
},
function(error){
dom.byId('studentFeedback').value += error;
}
);
});
</script>
</button><p>
<form>
Student feedback: <input id="studentFeedback"><p>
Student first name: <input id="studentFirstname"><p>
Student last name: <input id="studentLastname"><p>
Student id: <input id="studentId"><p>
</form>
<script src="dojo-release-1.12.2-src/dojo/dojo.js" data-dojo-config="async:true"></script>
<script type="text/javascript">
require(["dojo/parser", "dijit/form/Button", "dojo/domReady!"],
function(parser){
parser.parse();
});
</script>
</body>
</html>
data-dojo-props="iconClass:'dijitIconTask'
don't you need to end with "?
data-dojo-props="iconClass:'dijitIconTask'"
You can better the way you are creating JSON ex:
var json={};
json.name="Test";
json.age="23"
when you print json (JSON.stringify(json)), you will see
{
"name":"Test",
"age":"23"
}

How can i insert Multiple html into the modal through Javascript

Actually My question is after onclick My Modal is appear and i can insert multiple things into the Modal and i can do this through
(.html("abc");)
But the above syntax is insert only one string if i append multiple String it's shows error
Here is my Code:
echo "<script>
function myFunction(order){
$('.modal-body').html(order.order_id);
$('#myModal').modal({backdrop: false}); /#myModal is the body of the Modal
}
</script>";
Now i find out the soloution we can use this:
$('.modal-body').html('<b>Order Number</b>: '+order.order_id +
'<br>'+'<b>Order Date:</b>' + ' ' +order.created_date+ '<br>'+'<b>Table Number:</b>' + ' ' +order.uid + '<br>'+'<b>Status:</b> ' + ' ' +order.status+ '<br>'+'<b>Title:</b>' + ' ' +order.title + '<br>'+'<b>Quantity:</b>' + ' ' +order.quantity+ '<br>'+'<b>Personalization:</b>' + ' ' +order.personalization);

How to get Html code after javascript has modified it?

I want to get the HTML code of a webpage after it has been modified (similar to one that we see in inspect element tab of a browser) and I want to do it programatically (if possible using python or any other programming language). Can someone suggest how I might be able to proceed with this? I know its possible since browsers are able to do it.
As the server has no access to client window after client-side changes, you have to use client side languages.
In jquery:
var fullCode= "<html>" + $("html").html() + "</html>";
if you want also to include the Doctype:
var node = document.doctype;
var fullCode = "<!DOCTYPE "
+ node.name
+ (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '')
+ (!node.publicId && node.systemId ? ' SYSTEM' : '')
+ (node.systemId ? ' "' + node.systemId + '"' : '')
+ '>';
fullcode += "<html>" + $("html").html() + "</html>";
Thanks to this
Using JQuery you can achieve this by the following code
$(document).ready(function(){
var html = "<html>"+$('html').html()+"</html>";
});

Error in line of javascript 'missing ) after argument list"

I am trying to pass variables to a javascript function but i have the Javascript Error: 'missing ) after argument list"
html = html + '' + 'Lugar: ' +name.name +' Coordenadas: Lat '+ name.lat +' Lng'+ name.lng+ '<br>';
It doesn't look like I am missing any ')'s.
I see you have found your solution, but here's an alternative anyway, which reduces your string concatenation a little. There's still a far better way of achieving this, but this may help you start to see the benefit of moving away from building HMTL via string concatenation.
<meta charset="UTF-8">
<span id="spanTest"></span>
<script>
// Or whatever your initMap2 function does...
function initMap2(lat, lng, name) {
console.log('Lat: ' + lat);
console.log('Lng: ' + lng);
console.log('Name: ' + name);
}
var spanTest = document.getElementById('spanTest');
var worldLocation = { name:"test", lat:98.5, lng:-88.45 };
var anchor = document.createElement('a');
anchor.href = 'javascript:initMap2(' + worldLocation.lat +', ' + worldLocation.lng + ', \'' + worldLocation.name + '\');';
anchor.innerHTML = 'Name: ' + worldLocation.name + ', Lat: ' + worldLocation.lat + ' Lng: ' + worldLocation.lng;
spanTest.appendChild(anchor);
</script>
I'm assuming your last argument is expected to be a string, but it's resolved to look like a variable. Try this instead:
html = html + '<a href="javascript:initMap2(' + name.lat +','+ name.lng +',\''+ name.name +'\');">' // etc.
When name.name resolves to a string, it'll be wrapped in single quotes as expected. It'll look something like javascript:initMap2(1, 2, 'someString').

Internet Explorer open outlook appointment javascript

Go figure, I am having issues with IE and was hoping someone might be able to help....
I have a site where visitors will come and sign up for a specific meeting and then I want to be able to generate an appointment for the calendar of their choice; the choices are gmail, yahoo, and outlook. The gmail and yahoo appointments are generated as expected in all browsers, but the outlook appointments work in every browser except IE. Instead of throwing a file save dialog, IE opens a new window and attempts to navigate the url.
I am using the iCalendar jquery library that I modified a bit and building the ics markup in javascript, like this
//build ics markup
var event = makeAppointment(settings);
//render ics markup as outlook appointment
window.open("data:text/calendar;charset=utf8," + escape(event));
function makeAppointment()
{
return 'BEGIN:VCALENDAR\n' +
'VERSION:2.0\n' +
'PRODID:jquery.icalendar\n' +
'METHOD:PUBLISH\n' +
'BEGIN:VEVENT\n' +
'UID:' + new Date().getTime() + '#' +
(window.location.href.replace(/^[^\/]*\/\/([^\/]*)\/.*$/, '$1') || 'localhost') + '\n' +
'DTSTAMP:' + $.icalendar.formatDateTime(new Date()) + '\n' +
(event.url ? limit75('URL:' + event.url) + '\n' : '') +
(event.contact ? limit75('MAILTO:' + event.contact) + '\n' : '') +
limit75('TITLE:' + event.title) + '\n' +
'DTSTART:' + $.icalendar.formatDateTime(event.start) + '\n' +
'DTEND:' + $.icalendar.formatDateTime(event.end) + '\n' +
(event.summary ? limit75('SUMMARY:' + event.summary) + '\n' : '') +
(event.description ? limit75('DESCRIPTION:' + event.description) + '\n' : '') +
(event.location ? limit75('LOCATION:' + event.location) + '\n' : '') +
(event.recurrence ? makeRecurrence(event.recurrence) + '\n' : '') +
'END:VEVENT\n' +
'END:VCALENDAR';
}
You can get the file save dialog to work in IE by adding a "Content-Disposition: attachment" response header. However, this must happen on the server and cannot happen in client-side scripting, since JavaScript cannot modify header information.
See this answer for related details.

Categories

Resources