Sending XML in AJAX request always receives an error - javascript

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.

Related

How to download file using single ajax call?

This is my JavaScript code:
$.ajax({
type: 'GET',
url: GlobalConstant.serviceURL + "/CampaignReport/GetCampaignWiseTransactionData2?CampaignId=" + $scope.tempFilter.campaignId + "&endDate=" + JSON.parse(JSON.stringify($scope.tempFilter.endDate)) + "&startDate=" + JSON.parse(JSON.stringify($scope.tempFilter.startDate)),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (res) {
if (typeof res === 'string') {
toastr.error(res); // Data Not Available
}
else {
//Return ResponseMessageResult of C#
window.location.href = GlobalConstant.serviceURL + "/CampaignReport/GetCampaignWiseTransactionData2?CampaignId=" + $scope.tempFilter.campaignId + "&endDate=" + JSON.parse(JSON.stringify($scope.tempFilter.endDate)) + "&startDate=" + JSON.parse(JSON.stringify($scope.tempFilter.startDate));
}
},
error: function (res) {
//Server Error
toastr.error("Oops something went wrong, Please try again later.");
}
})
But here I am calling the api two times. first I check there is data available or not if data available then I will call for download how can I achieve in single call.

ajax sometimes returns #document, sometimes Object{d:Object}

When I check console in Chrome, the Sharepoint page behaves as it is supposed to when data is Object {d: Object} and d is an Array of the items of want.
When data is #document, the page does not load as I append html based on data.
I understand #document appears because of jQuery's Intelligent Guess, but am not sure why it is getting returned.
function getItems() {
var url = hostWebURL + "_api/web/lists('" + guid + "')/items/";
var items;
$.ajax({
url: url,
type: "GET",
headers: { "Accept": "application/json;odata=verbose "}, // return data format
success: function (data) {
//items is iterable ListItemCollection
console.log(data);
items = data.d.results;
...
},
error: function (error) {
var errorMsg = "";
if (error.status == "403" || error.status == "401") {
errorMsg = "You do not have Authorization to see Site Permissions - ErrorCode(" + error.status + ") Error Details: " + error.statusText;
}
else {
var errorMsg = "Failed - ErrorCode(" + error.status + ") Error Details: " + error.statusText;
}
reportError(errorMsg);
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json; odata=verbose");
Added this parameter to the call and it's working!
Taken from: http://ratsubsharewall.blogspot.com/2017/02/rest-call-returns-xml-instead-of-json.html

jquery ajax inside loop return statusText error, Status 0 after certain time in IE

I m trying to update bulk of data one by one using Jquery ajax,so that i can show update progress. every thing goes well at beginning but after 5 min, it throw an error like in
Image while checking network request/respond:.
Error on error function of ajax:.
MainData is array of json object and is contain around 3000 number of json object.
function DoPost()
{
$.each(MainData, function (key, value) {
var mainCode = value.MainCode;
var companyCode = value.CompanyCode;
$.ajax({
url: "Allotment.asmx/DoAllotment",
data: "{MainCode:'" + mainCode + "', sNoOfAllotment:'" + noOfAllot + "',CompanyCode:'" + companyCode + "'}",
dataType: 'text',
contentType: "application/json; charset=utf-8",
type: "Post",
success: function (res){
Progress(res); // this funtion will show progress of update.
},
error: function (res) {
console.log(res);
}
});
});
}
I am using web service of asp.net webform
The issue could be maximum number of concurrent connections to same URL. You can schedule next $.ajax() call when current $.ajax() completes.
See also multiple, sequential fetch() Promise
function DoPost(value) {
var mainCode = value.MainCode;
var companyCode = value.CompanyCode;
return $.ajax({
url: "Allotment.asmx/DoAllotment",
data: "{MainCode:'" + mainCode + "', sNoOfAllotment:'"
+ noOfAllot + "',CompanyCode:'" + companyCode + "'}",
dataType: 'text',
contentType: "application/json; charset=utf-8",
type: "POST",
success: function(res) {
Progress(res); // this funtion will show progress of update.
},
error: function(res) {
console.log(res);
}
});
}
var copy = MainData.slice(0);
var res = (function re(value) {
return DoPost(value).then(function() {
return copy.length ? re(copy.shift()) : "complete"
})
})(copy.shift());
res.then(function(complete) {
console.log(complete)
}, function(err, textStatus, jqxhr) {
console.log(err)
});
The error 0x2ee2 is IE's representation of timeout error. The occurrence of this error shows that the server has stopped responding to the requests due to a high number of requests sent from the same client. This is the server avoiding DOS attacks from the client.
The proper method is to optimize the code and try to utilize the maximum available bandwidth in order to minimize the number of requests to the server.

POST http://localhost:51348/TestService.svc/SendCredentials 400 (Bad Request)

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));

jQuery AJAX and IE8 outputs "Invalid argument"

guys!
It is very strange thing. This code normally works in all browsers I know, except IE8 (may be IE7 too).
function xajax_xfrmproc(sender, eventname, data, formname, data2) {
var dt = {};
dt.__xr = 1; // AJAX request flag
dt.__sender = sender;
dt.__eventname = eventname;
dt.__data = data;
dt.__formname = formname;
dt.__data2 = data2;
$.ajax({
type: 'POST',
url: '',
data: dt,
error: function(req, text, error) {
alert('AJAX Error: ' + text + ' | ' + error + ':' + "\n" + req.responseText);
},
success: function (json) {
jxr_decode(json);
},
dataType: "json"
});
}
It calls error method and writes: "AJAX Error: error | Error: Invalid argument".
You can test is online here: http://stat.8-800.su (enter any values and press "Войти в статистику" button).
I check in over all internet but not found anything useful.
I've tried to set AddDefaultCharset utf-8, nothing happens.
This is a stab, but try using the actually URL instead of the empty string. So
url: '/',

Categories