I have a fairly simple web service response. How I can parse the response in a way that I could get the value of namespace ns2:count.
Web Service Response
<availableSlots xmlns:ns5="http://jabber.org/protocol/httpbind" xmlns:ns2="http://bindings.egain.com/chat" xmlns:ns4="urn:ietf:params:xml:ns:xmpp-stanzas" xmlns:ns3="jabber:client">
<ns2:count>1</ns2:count>
</availableSlots>
My JavaScript
$(document).ready(function () {
$.ajax({
url: "https://myserver/system/company/chat/fake/capacity/1007",
dataType: 'xml',
success: function (data) {
var xmlDoc = $.parseXML(data),
$xml = $(xmlDoc),
$name = $xml.find("ns2\\:count");
$("#AvailableAgents").html($name);
alert($name);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText + "\n" + xhr.status + "\n" + thrownError);
}
});
});
this way my alert shows object [Object]. How I can get the value 1.
Unfortunately, parseXML dose not work for me but I was able to get the values as;
I get the xml attribute which is availableSlots
Then I get the valueof ns2 namespace
var slots = $(data).find('availableSlots');
var numberOfAgents = $(slots).find("ns2\:count").text();
Related
I am sending XML to a particular web service. When I view the response in my browser's network tab, it seems it's a proper request as I expected, but still the error callback in my JS code is firing hence handling it as an error instead of making use of the returned response as expected. What could be the cause of this?
const endpoint = "https://secure1.sandbox.directpay.online/API/v6/";
$(document).ready(function() {
$("#sendBtn").click(function() {
var x2js = new X2JS();
var req = "<?xml version='1.0' encoding='utf-8'?>" +
"<API3G>" +
"<CompanyToken>TOKEN-TO-BE-PLACED-HERE</CompanyToken>" +
"<Request>createToken</Request>" +
"<Transaction>" +
"<PaymentAmount>450.00</PaymentAmount>" +
"<PaymentCurrency>USD</PaymentCurrency>" +
"<CompanyRef>49FKEOA</CompanyRef>" +
"<RedirectURL>https://secure1.sandbox.directpay.online/payv2.php?ID=TOKEN-HERE</RedirectURL>" +
"<BackURL>http://localhost/computicket_node_server/</BackURL>" +
"<CompanyRefUnique>0</CompanyRefUnique>" +
"<PTL>5</PTL>" +
"</Transaction>" +
"<Services>" +
"<Service>" +
"<ServiceType>5525</ServiceType>" +
"<ServiceDescription>Flight from Malawi to India</ServiceDescription>" +
"<ServiceDate>2013/12/20 19:00</ServiceDate>" +
"</Service>" +
"</Services>" +
"</API3G>";
$.ajax({
url: endpoint,
type: "POST",
data: req,
//timeout: 5000,
dataType: "text/xml",
success: function(response) {
var res = JSON.stringify(x2js.xml_str2json(response));
console.log(res);
document.getElementById("response").innerHTML = res;
},
error: function(xhr, status, error) {
console.log(xhr, status, error);
}
});
});
});
The results that I am getting
Is dataType not the responding type? You should use contentType
contentType: "application/xml",
Don't know what type you expect to get back, I think you can avoid it.
I have been stuck at this problem for almost two days now and I don't seem to find any solution. I have hosted a WCF service on my machine that contains a method SendCredentials which accepts two string parameters.
Now I am supposed to send a public key to my service through which it will do encryption(Asymetric cryptography) and send some information back to the client.
I am not able to pass that public key to the service method from the client as it is in XML format.Here is my client side code:
$(document).ready(function () {
$("#btnSend").click(function () {
debugger;
jQuery.support.cors = true;
var doOaepPadding = true;
var rsa = new System.Security.Cryptography.RSACryptoServiceProvider();
_privateKey = rsa.ToXmlString(true);
_publicKey = rsa.ToXmlString(false);
var data = $("#txtName").val();
var name = "testvalue";
var _privateKey = rsa.ToXmlString(true);
**var _publicKey = rsa.ToXmlString(false);**
//<![CDATA[ and ]]>;
$.ajax({
type: "POST",
url: 'http://localhost:51348/TestService.svc/SendCredentials',
crossDomain: true,
data:JSON.stringify({ mac: "bac", pubKey: _publicKey }),
contentType: "application/json",
dataType: "json",
success: function (result) {
var ans = JSON.stringify(result);
alert(ans);
// result = new XMLSerializer().serializeToString(result.documentElement);
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
});
return false;
});
});
</script>
_publicKey is the variable I want to pass but throws above said error. Any suggestions How do i pass this XML variable would be really appreciated.
I would suggest you to convert _publicKey to base64 string
convert your _publicKey to string then byte Array and use
Convert.ToBase64String(byte[] inArray)
and on the service side do the reverse
System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(endodedString), true));
I am working a visual studio 2012 MVC program.
I use ajax to send data to a controller and wish the controller returns a body of html. the data is in json format. the data is a string name and decimal TotFees.
I found that the parameters value in the public ActionResult ImmPay(string Name) in the controller are always null. Finally I tried just to pass name, but the value of name in the controller side is still null.
what is wrong in my code, and how to solve the problem? Thank you.
View:
function ImmPay()
{
var name = "ASP";
var TotFees = 100.01;
//var dd = "{\'name\':\'" + name + "\', \'TotFees\':\'" + TotFees + "\'}";
//var dd = "{\'name\':\'" + name + "\', \'TotFees\':\'" + TotFees + "m\'}";
dd = "{\'b\':\'" + b + "\'}";
dd = JSON.stringify(dd);
$.ajax({
url: '#Url.Action("ImmPay", "Consult")',
type: 'GET',
async: true,
data: dd,
contentType: 'application/json',
context: document.body,
success: function (response, textStatus, jqXHR) {
$("#dialog-immpay").html(response);
$("#dialog-immpay").dialog("open");
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
},
complete: function () {
;
}
});
}
Controller:
public ActionResult ImmPay(string Name)
{
do something here
}
JSON.stringify takes an object or an array and converts it into JSON, so you can build your data into an object and stringify it like so
dd = JSON.stringify({b: b});
I'm having an issue using JOSN data in MS CRM 2011. I am using the correct REST syntax to pull the CRM data but my JavaScript is the remaining issue.
What I want to do is append data from my JSON to a class of my choosing. I checked the console and no errors are apparent. Originially I believed once I had the JSON object I could pull the data from it using jQuery. Here is the code I currently have:
RetrieveScoutMetadata : (function(scout_displayable){
var query = "/scout_metadataSet?$select=scout_data_type,scout_display_name,scout_display_order,scout_displayable,ImportSequenceNumber,scout_name,scout_metadataId&$orderby=scout_display_order asc&$filter=scout_displayable eq "+scout_displayable+"";
ExecuteQuery(query);
})
RetrieveScoutOpportunity : (function(scout_account){
var query = "/scout_opportunitySet?$select=*&$filter=scout_account/Id eq guid'"+scout_account+"'";
ExecuteQuery(query);
})
RetrieveScoutAccount : (function(scout_account){
var query = "/scout_accountSet?$select=*&$filter=scout_account/Id eq guid'"+scout_account+"'";
ExecuteQuery(query);
})
//
// ExecuteQuery executes the specified OData Query asyncronously
//
// NOTE: Requires JSON and jQuery libraries. Review this Microsoft MSDN article before
// using this script http://msdn.microsoft.com/en-us/library/gg328025.aspx
//
function ExecuteQuery(ODataQuery) {
var serverUrl = Xrm.Page.context.getServerUrl();
// Adjust URL for differences between on premise and online
if (serverUrl.match(/\/$/)) {
serverUrl = serverUrl.substring(0, serverUrl.length - 1);
}
var ODataURL = serverUrl + "/XRMServices/2011/OrganizationData.svc" + ODataQuery;
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: ODataURL,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
//
// Handle result from successful execution
//
// e.g. data.d.results
alert("OData Execution Success Occurred");
},
error: function (XmlHttpRequest, textStatus, errorObject) {
//
// Handle result from unsuccessful execution
//
alert("OData Execution Error Occurred");
}
});
$('.up-sell').append(account.scout_num_up_sells);
}
//
// Error Handler
//
function ErrorHandler(XMLHttpRequest, textStatus, errorObject)
{ alert("Error Occurred : " + textStatus + ": " + JSON.parse(XMLHttpRequest.responseText).error.message.value); }
To get response use "complete" function:
complete: function (jsondata, stat) {
if (stat == "success") {
data = JSON.parse(jsondata.responseText);
}
}
We have a .asmx service that returns JSON data. Can someone point me to a simple example that calls the service from a page w JavaScript ?
Tks
You can use jQuery's get function.
var dataID = $('#WhatINeedForAParameter').val();
$.get('WebApiAddress/MethodName', { id: dataID },
function(data) {
alert(data);
// Since your method returns a JSON object you can access
// the properties of that object
alert(data.id);
alert(data.name);
});
Or if you want to use the long hand jQuery ajax you can do the following:
var dataID = $("#WhatINeedForAParameter").val();
var request = $.ajax({
url: "WebApiAddress/MethodName",
type: "POST",
data: { id : dataID },
dataType: "jsonp"
});
request.done(function(msg) {
alert('You got this ' + msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Your request failed: " + textStatus );
});