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.
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.
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
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.
This question already has answers here:
how to access the $(this) inside ajax success callback function
(6 answers)
Closed 8 years ago.
I have instantiated the JavaScript object "User". It contains all the necessary for the user management. Even loading and possible AJAX error are managed here.
Below there's a snapshot of this object.
var User = function(uid, ajaxURL) {
this.uid = uid;
this.ajaxURL = ajaxURL;
};
User.prototype = {
loadingShow: function (tag) {
this.tag = (tag) ? tag : '.tab-pane';
$(this.tag + ' .loading').html('<img src="img/template/loading.gif" alt="Loading..." title="Loading...">').fadeIn('fast');
},
//...
};
User.prototype.loadAction = function (rel) {
var utls = new User();
var relAttr = rel;
$.ajax({
type: 'POST',
url: this.ajaxURL + '&id=' + parseInt(this.uid),
cache: true,
dataType: 'json',
data: {
toDo: relAttr
},
beforeSend:function(){
utls.loadingShow('#' + relAttr + '-tab');
},
//...
It works fine but i have just a question, perhaps stupid but I'm facing for first times JavaScript OOP and Prototype-Based-programming.
Why must i create var utls = new User(); for call this utls.loadingShow( and not simply call it by this.loadingShow(?
Using the this property i obtain the error "TypeError: this.loadingShow is not a function".
"Why must i create var utls = new User(); for call this utls.loadingShow( and not simply call it by this.loadingShow(?"
Because this in the callback is set to the jqXHR object.
To override it, you can set the context: property of the $.ajax request to the this value that you want.
$.ajax({
type: 'POST',
url: this.ajaxURL + '&id=' + parseInt(this.uid),
cache: true,
dataType: 'json',
context: this, // <-- set the `this` value of the callbacks
data: {
toDo: relAttr
},
beforeSend:function(){
// v--- now it's correct
this.loadingShow('#' + relAttr + '-tab');
},
success: function(data) {
var art_tmp_str = '';
// Why are you using this? ---v
// $(document).ajaxComplete(function(event, request, settings) {
// v--- now it's correct
this.loadingHide('#' + relAttr + '-tab');
$('#' + relAttr + '-tab').html('');
if(data.success === true) {
// v--- now it's correct
art_tmp_str = this.writeAction(relAttr, data);
$('#' + relAttr + '-tab').append(art_tmp_str);
} else
$('#' + relAttr + '-tab').append('<p>' + data.error + '</p>');
// });
Furthermore, there shouldn't be any need to give a handler to .ajaxComplete() when you're already in a success callback. This should be done before any ajax requests are made if you really want a single behavior applied to all completed requests.
I got an Ajax function that looks like this
function PersonAtlLawUpdate(personRef) {
var selectionPanel = $('div#SelectionPanel');
var fromdate = selectionPanel.find('input#FromDateTextBox')[0].defaultValue;
var timeSpan = selectionPanel.find('select#TimeSpanDropdownList').data('timespanvalue');
var url = "MonthOverview.aspx/OnePersonAtlLawUpdate";
$.ajax({
url: url,
data: JSON.stringify({ personRef: personRef, fromdate: fromdate, timespan: timeSpan }),
type: "POST",
contentType: "application/json",
dataType: "JSON",
context: document.body,
success: function (atlError) {
changePersonAtlStatusIcon(atlError, personRef);
},
error: function (xhr, status, errorThrown) {
//alert(errorThrown + '\n' + status + '\n' + xhr.statusText);
}
});
}
In one function I need to run this twice like this:
PersonAtlLawUpdate($(gMarkedCell).parent("tr").attr("personref"));
PersonAtlLawUpdate(pRef);
The problem that can be is that in some cases doesn't work 100%. The dom doesnt update in one of the functions. And I think it is because the other one "overwrites" it.
So how do I make sure that the second "PersonAtlLawUpdate" runs after the first one completes? Doesnt seems good to put a delay on it. And is it a good solution to set async to false in the ajax call?
EDIT,
tride like this and placed a console.log in my success. But "all complete" will run first of them:
$.when(PersonAtlLawUpdate($(gMarkedCell).parent("tr").attr("personref")), PersonAtlLawUpdate(pRef)).then(function (){console.log("all complete")});
You can just use a callback function so that it executes right after the first one has executed:
PersonAtlLawUpdate($(gMarkedCell).parent("tr").attr("personref"), function(){
PersonAtlLawUpdate(pRef);
});
Or maybe you can rethink the problem, and come up with a solution that doesn't require calling the same function twice. Maybe you don't really need to do this.
I think what #Kyokasuigetsu suggests is you need to alter the PersonAtlLawUpdate method so that is accepts an optional second parameter: a callback function that need to be called in the success callback.
function PersonAtlLawUpdate(personRef, cbFunc) {
var selectionPanel = $('div#SelectionPanel');
var fromdate = selectionPanel.find('input#FromDateTextBox')[0].defaultValue;
var timeSpan = selectionPanel.find('select#TimeSpanDropdownList').data('timespanvalue');
var url = "MonthOverview.aspx/OnePersonAtlLawUpdate";
$.ajax({
url: url,
data: JSON.stringify({ personRef: personRef, fromdate: fromdate, timespan: timeSpan }),
type: "POST",
contentType: "application/json",
dataType: "JSON",
context: document.body,
success: function (atlError) {
changePersonAtlStatusIcon(atlError, personRef);
if (cbFunc != null)
cbFunc();
},
error: function (xhr, status, errorThrown) {
//alert(errorThrown + '\n' + status + '\n' + xhr.statusText);
}
});
And than make the call as;
PersonAtlLawUpdate($(gMarkedCell).parent("tr").attr("personref"), function(){
PersonAtlLawUpdate(pRef);
});
Your example will work fine if you return your $.ajax calls from your PersonAtLawUpdate function.
$.when needs a reference to the ajax calls, so make sure you return the Deferred (the ajax call) from your functions
function PersonAtlLawUpdate(personRef) {
var selectionPanel = $('div#SelectionPanel');
var fromdate = selectionPanel.find('input#FromDateTextBox')[0].defaultValue;
var timeSpan = selectionPanel.find('select#TimeSpanDropdownList').data('timespanvalue');
var url = "MonthOverview.aspx/OnePersonAtlLawUpdate";
//SEE THE NEXT LINE
return $.ajax({
url: url,
data: JSON.stringify({ personRef: personRef, fromdate: fromdate, timespan: timeSpan }),
type: "POST",
contentType: "application/json",
dataType: "JSON",
context: document.body,
success: function (atlError) {
changePersonAtlStatusIcon(atlError, personRef);
},
error: function (xhr, status, errorThrown) {
//alert(errorThrown + '\n' + status + '\n' + xhr.statusText);
}
});
}
Use:
$.when(PersonAtLawUpdate(ref1), PersonAtLawUpdate(ref2)).done(function(xhrRef1, xhrRef2) {
//do stuff w/ results from both calls
//if you return something from the server,
//the results will be available in xhrRef1[0]
//and xhrRef2[0], respectively (order they
//appear in the when(), not in the order they execute
});