Unable to send dynamic invoice value to struts2 server - javascript

I am working on angularjs 1.6.5
I am using following code to send data of invoice page.
$scope.products = [{qty: 0, description: ' ', sellingPrice: 0.0, unitPrice: 0.0, total: 0.0}];
$scope.fproducts = [];
$scope.generateInvoice = function () {
console.log("generateInvoice");
console.log($scope.fproducts);
console.log("sub total " + $scope.subTotal + " ft " + $scope.finalTotal + " pamt " + $scope.paidAmount + " baldue " + $scope.balancedue);
$scope.bd1 = {
'subTotal': $scope.subTotal,
'total': $scope.finalTotal,
'TotalPaid': $scope.paidAmount,
'invDateStr': $filter('date')($scope.invoiceDate, "MM/dd/yyyy"),
};
if ($scope.fproducts.length > 0) {
$scope.fproducts.forEach((total, index) => {
Object.entries(total).forEach(([key, value]) => {
console.log(index + " " + key + " " + value);
$scope.bd1[`billProductList[${index}].${key}`] = value;
});
});
}
//commenting above for each and removing comment from below code is
// working properly but I want to send dynamic data with above code
/* $scope.bd1[`billProductList[0].id`] = 1;
$scope.bd1[`billProductList[0].description`] = 1;
$scope.bd1[`billProductList[0].discountPercent`] = 150;
$scope.bd1[`billProductList[0].qty`] = 10;
$scope.bd1[`billProductList[0].sellingPrice`] = 100;
$scope.bd1[`billProductList[0].unitPrice`] = 100;
$scope.bd1[`billProductList[0].total`] = 150;*/
$scope.bd1[`BillPaidDetailses[0].paymentMode`] = $scope.paymentMode;
$scope.bd1[`BillPaidDetailses[0].amount`] = $scope.paidAmount;
console.log($scope.bd1);
$http({
method: 'POST',
url: 'added-invoice',
data: $httpParamSerializerJQLike($scope.bd1),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(data, status, headers, config) {
if (data.data.st === 1) {
$scope.success = true;
window.location = 'bhome#!/show-tax';
} else if (data.data.st === 0) {
$scope.success = false;
$scope.failure = true;
} else if (data.data.st === -1) {
$scope.success = false;
$scope.failure = true;
}
}, function errorCallback(data, status, header, config) {
$scope.success = false;
$scope.failure = true;
});
}
Above code is not passing value to server side object.
its console.log value is
on modifying above data
/*if ($scope.fproducts.length > 0) {
$scope.fproducts.forEach((total, index) => {
Object.entries(total).forEach(([key, value]) => {
console.log(index + " " + key + " " + value);
$scope.bd1[`billProductList[${index}].${key}`] = value;
});
});
}*/
$scope.bd1[`billProductList[0].id`] = 1;
$scope.bd1[`billProductList[0].description`] = 1;
$scope.bd1[`billProductList[0].discountPercent`] = 150;
$scope.bd1[`billProductList[0].qty`] = 10;
$scope.bd1[`billProductList[0].sellingPrice`] = 100;
$scope.bd1[`billProductList[0].unitPrice`] = 100;
$scope.bd1[`billProductList[0].total`] = 150;
as this is passing value to server object
its console.log is
I want to run my code using dynamic value specified in if condition.
What is the problem I am unable to get it.
EDIT I am using server side struts2
my code is
public class BillNewAction extends ActionSupport implements ModelDriven<BillDetails> {
BillDetails bd = new BillDetails();
private List<BillDetails> billList = new ArrayList<BillDetails>();
public String insert() {
System.out.println("total " + bd.getTotal()
+ " subTotal " + bd.getSubTotal() + " paid "
+ bd.getTotalPaid()
+ " invoiceDate " + bd.getInvDateStr()
);
SimpleDateFormat formatter1 = new SimpleDateFormat("MM/dd/yyyy");
try {
bd.setInvoiceDate((new java.sql.Date(formatter1.parse(bd.getInvDateStr()).getTime())));
} catch (ParseException ex) {
Logger.getLogger(BillNewAction.class.getName()).log(Level.SEVERE, null, ex);
}
for (BillPaidDetails b : bd.getBillPaidDetailses()) {
System.out.println("type " + b.getPaymentMode() + " amount "
+ b.getAmount()
);
}
System.out.println("product size " + bd.getBillPrList().size());
for (BillProduct b : bd.getBillPrList()) {
System.out.println("id " + b.getId() + " desc "
+ b.getDescription() + " qty " + b.getQty()
+ " sp " + b.getSellingPrice() + " up "
+ b.getUnitPrice() + " " + b.getTotal()
);
}
}
}
public class BillDetails implements java.io.Serializable {
private Long billNo;
private Client client;
private BigDecimal subTotal;
private BigDecimal TotalAmount;//total price
private BigDecimal TotalPaid;//Amount paid for getting items
private BigDecimal vat;
private BigDecimal total;
private String invoiceNo;
private Date invoiceDate;
private String invDateStr;
private List<BillPaidDetails> BillPaidDetailses = new ArrayList<BillPaidDetails>();
private List<BillProduct> billPrList = new ArrayList<BillProduct>();
//getter and setter
}
I have to send data in $scope.bd1[billProductList[0].id] = 1; format to server
Assigning indivisual value passing the data to server but I have dynamic no of values so I am trying
if ($scope.fproducts.length > 0) {
$scope.fproducts.forEach((total, index) => {
Object.entries(total).forEach(([key, value]) => {
console.log(index + " " + key + " " + value);
$scope.bd1[billProductList[${index}].${key}] = value;
});
});
}
that is not working

Consider using the Struts JSON Plugin
The JSON plugin provides a json result type that serializes actions into JSON.
The content-type must be application/json
Action must have a public “setter” method for fields that must be populated.
Supported types for population are: Primitives (int,long…String), Date, List, Map, Primitive Arrays, other class, and Array of Other class.
Any object in JSON, that is to be populated inside a list, or a map, will be of type Map (mapping from properties to values), any whole number will be of type Long, any decimal number will be of type Double, and any array of type List.
Your actions can accept incoming JSON if they are in package which uses json interceptor or by adding reference to it.
This simplifies the AngularJS HTTP POST request:
$scope.bd1 = {
'subTotal': $scope.subTotal,
'total': $scope.finalTotal,
'TotalPaid': $scope.paidAmount,
'invDateStr': $scope.invoiceDate.toISOString(),
'billProductList': $scope.fproducts,
};
$http({
method: 'POST',
url: 'added-invoice',
data: $scope.bd1,
headers: {'Content-Type': 'application/json'}
}).then(function successCallback(response) {
var data = response.data;
if (data.st === 1) {
$scope.success = true;
window.location = 'bhome#!/show-tax';
} else if (data.st === 0) {
$scope.success = false;
$scope.failure = true;
} else if (data.data.st === -1) {
$scope.success = false;
$scope.failure = true;
}
}, function errorCallback(response) {
$scope.success = false;
$scope.failure = true;
});

$scope.bd1[billProductList[${index}].${key}] = value; you are overriding value on this line of code
$scope.bd1[billProductList[${index}${index2}].${key}] you can change shape of object as per you need
$scope.fproducts.forEach((total, index) => {
Object.entries(total).forEach(([key, value],index2) => {
console.log(index + " " + key + " " + value);
$scope.bd1[`billProductList[${index}${index2}].${key}`] = value;
});
})

That may be because console.log(index + " " + key + " " + value) is returning correct value as you are getting inside loop.
try to access the below piece of code, after assigning to $scope.bd1:
Object.entries(total).forEach(([key, value]) => {
$scope.bd1[`billProductList[${index}].${key}`] = value;
console.log($scope.bd1[`billProductList[${index}].${key}`]);
});
And I guess $scope.bd1 is not getting updated hence it is not passing value to server side object.

Related

Filter data obtained through GitHub API

I created this function to obtain GitHub issues:
retrieveEnerpriseIssues: function(repoOrg, repoName, callback) {
let data = null;
// token auth
octokit.authenticate({
type: 'basic',
username: config.githubEnterprise.username,
password: config.githubEnterprise.token
});
async function paginate(method) {
let response = await method({
q: "repo:" + repoOrg + "/" + repoName + " is:issue",
per_page: 100
});
data = response.data.items;
var count = 0;
while (octokit.hasNextPage(response)) {
count++;
console.log(`request n°${count}`);
response = await octokit.getNextPage(response);
data = data.concat(response.data.items);
}
return data;
}
paginate(octokit.search.issues)
.then(data => {
callback(data);
})
.catch(error => {
console.log(error);
});
}
It is called in this function which takes the issues, filters out all of the unwanted keys into json format and puts it in my db.
extractToDb: function() {
let gitIssues = null;
for(var i = 0; i < config.githubEnterprise.orgs.length; i++) {
for(var j = 0; j < config.githubEnterprise.orgs[i].repos.length; j++) {
gitHubService.retrieveEnerpriseIssues(
config.githubEnterprise.orgs[i].owner,
config.githubEnterprise.orgs[i].repos[j].repoName,
function(data, err) {
if(err) {
console.log('err: ', err);
} else {
gitIssues = data;
}
gitIssues = JSON.stringify(gitIssues);
gitIssues = JSON.parse(gitIssues);
let issueFormatForDb = null;
for(var i = 0; i < gitIssues.length; i++) {
issueFormatForDb = gitIssues[i];
const body = '{' +
'"github_id": "' + issueFormatForDb.id + '",' +
'"issue_title": "' + issueFormatForDb.title + '",' +
'"issue_number": "' + issueFormatForDb.number + '",' +
'"issue_url": "' + issueFormatForDb.url + '",' +
'"issue_state": "' + issueFormatForDb.state + '"' +
'}';
console.log('Body: ', body);
getGitHubIssues.postToDb(body);
}
});
}
}
}
I'd like to take this a step further by filtering out any issues where the state is closed. How is this done and should it be handled in my retrieveEnerpriseIssues function or my extractToDb?
Possible solution
I tried this in my extractToDb function:
gitIssues = JSON.parse(gitIssues);
gitIssues = _.where(gitIssues, {state: "open"});
let issueFormatForDb = null;
Is it the best solution or is there a better way?
As #givehug stated:
Better use _.filter, or native filter method like
gitIssues = gitIssues.filter(i => i.state === 'open')
I think .where was deprecated in later versions of lodash github.com/lodash/lodash/wiki/Deprecations. Other than that its perfectly fine.
I just realsied I can filter the state in my paginate function with this:
let response = await method({
q: "repo:" + repoOrg + "/" + repoName + " is:issue" + " label:issue_label" + " state:open",
per_page: 100
});

Javascript unable to get control out of method

I have few problems with below code.Can anyone help?
The if (currentStatus!="undefined") block in getStatusUsingAjax methid is not working.
unable to get the control out of getStatusUsingAjax method
$(document).ready(
loadStatus()
);
function loadStatus(x) {
$('.a-IRR-table tr').each(function(i) {
var val = $(this).find("td").eq(0).text();
link = $(this).find("td").eq(0).find("a").attr("href");
linkTag = $(this).find("td").eq(0).find("a");
`if ((val !== "-") && (val !== "")) {
console.log("val is" + val);
if (verifyrequestArray(val)) {
console.log("inside second if");
} else {
console.log("inside else");
sleep(1.5 * 1000);
var updatedStatus2 = getStatusUsingAjax(val, link);
console.log("UpdatedStatus2 is " + updatedStatus2);
setTooltip(linkTag, updatedStatus2);
}
}
});
}
function verifyrequestArray(id) {
var newArray = requestArray.toString().split('-');
console.log("NewArray is :" + newArray);
for (i = 0; i < newArray.length; i++) {
// I'm looking for the index i, when the condition is true
if (newArray[i] === id) {
console.log("request id found" + newArray[i]);
break;
} else {
console.log("request id not found" + newArray[i]);
return false;
}
}
}
function getStatusUsingAjax(requestValue, currentlink) {
console.log("patch req: " + requestValue);
console.log("Link is " + currentlink);
var currentStatus;
GM_xmlhttpRequest({
method: "GET",
url: currentlink,
onload: function(response) {
if ($(response.responseText).find("#P16_STATUS2").size() === 1) {
currentStatus = $(response.responseText).find("#P16_STATUS2").text();
console.log("Current Status from #P16_STATUS2 is :" + currentStatus);
console.log("Final URL is " + response.finalUrl);
}
}
});
// console.log("Final URL is " +response.finalUrl);
if (currentStatus != "undefined") {
var pusharr = [requestValue + "-" + currentStatus];
requestArray.push(pusharr);
console.log("Updated Array is " + requestArray);
return currentStatus;
}
}
function setTooltip(currentTag, status2) {
console.log("in settooltip" + currentTag);
currentTag.attr("title", status2); //setting status a tooltip
}
Any clue where the error is?
fn getStatusUsingAjax is async, you can not get return value using:
var updatedStatus2 = getStatusUsingAjax(val, link);
You sholud create callback:
function getStatusUsingAjax(val, link, callback){
//...
// do not use return currentStatus, call calback fn instead
callback(currentStatus)
}
and call it using:
getStatusUsingAjax(val, link, function(updatedStatus2){
console.log("UpdatedStatus2 is " + updatedStatus2);
setTooltip(linkTag, updatedStatus2);
});

How to sort data of json object and display accordingly in html?

This is my ajax:
$("form").on("submit", function () {
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "ajax2.php",
data: data,
success: function (data) {
$("#main_content").slideUp("normal",function(){
//$(".the-return").html("<br />JSON: " + data+"<br/>");
for (i = 0; i < data.length; i++) {
$(".the-return").append("<div class='inside_return'>Name:" + data[i].name + "<br/>Id:" + data[i].id + "<br/>Pricing:" + data[i].rate + "<br/>Postcode:" + data[i].postcode+ "<br/>Reputation:" + data[i].reputation+"<br/>Review Plus:" + data[i].plus+"<br/>Review Negative:" + data[i].neg+"<br/><h1>Availability</h1>Week Morning:" + data[i].weekM+"<br/>Week Afternoon:" + data[i].weekA+"<br/>Week Evening:" + data[i].weekE+"<br/>Weekend Morning:" + data[i].endM+"<br/>Weekend Afternoon:" + data[i].endA+"<br/>Week Evening:" + data[i].endE+"</div>");
//alert(data[i].name)
}
});
}
});
return false;
});
Above is my ajax. Now this is returning result from query that sorts by postcode by default.
Now when the result displayed, I want to let the user to sort it out by reputation, review and so on..How do I do that.
Put it in a simple way, I just need to alter the order by clause in the query so that it can sort by user selection. What's the easiest way to do it please?
How can I manipulate below part where it appends the result to a div called -the-return so that it sorts by whatever key user use?: Note-> I'm presenting the result in <div> block and not in table.
$(".the-return").append("<div class='inside_return'>Name:" + data[i].name + "<br/>Id:" + data[i].id + "<br/>Pricing:" + data[i].rate + "<br/>Postcode:" + data[i].postcode+ "<br/>Reputation:" + data[i].reputation+"<br/>Review Plus:" + data[i].plus+"<br/>Review Negative:" + data[i].neg+"<br/><h1>Availability</h1>Week Morning:" + data[i].weekM+"<br/>Week Afternoon:" + data[i].weekA+"<br/>Week Evening:" + data[i].weekE+"<br/>Weekend Morning:" + data[i].endM+"<br/>Weekend Afternoon:" + data[i].endA+"<br/>Week Evening:" + data[i].endE+"</div>");
WHat I tried:
success: function (data) {
//I used a function to sort//
data.sort(function (a, b) {
var retVal = 0;
switch (sortOption) {
case 1:
retVal = a.property > b.property ? 1 : (a.property < b.property ? -1 : 0);
break;
// .... many cases here
}
return retVal;
});
//sort function ends here//
$("#main_content").slideUp("normal", function () {
for (i = 0; i < data.length; i++) {
$(".the-return").append("<div class='inside_return'>Name:" + data[i].name + "<br/>Id:" + data[i].id + "<br/>Pricing:" + data[i].rate + "<br/>Postcode:" + data[i].postcode + "<br/>Reputation:" + data[i].reputation + "<br/>Review Plus:" + data[i].plus + "<br/>Review Negative:" + data[i].neg + "<br/><h1>Availability</h1>Week Morning:" + data[i].weekM + "<br/>Week Afternoon:" + data[i].weekA + "<br/>Week Evening:" + data[i].weekE + "<br/>Weekend Morning:" + data[i].endM + "<br/>Weekend Afternoon:" + data[i].endA + "<br/>Week Evening:" + data[i].endE + "</div>");
}
});
}
so when a user clicks a button, it fire the sorting function..Sadly it doesn't work..Placing the function within success, doesn't perform search function it was doing earlier without any sort. Even if I placed it outside the function , still doesn't work.
To sort an array, you can use Array.prototype.sort.
Without any arguments, it attempts to sort elements alphabetically, but you can pass in a comparing function instead.
The function will receive two arguments and should return less than 0, 0 or greater than 0 to define where argument 1 should be in relation to argument 2.
Your sorting function should look something like this:
data.responseData.sort(function (a, b) {
switch (sortOption) {
case 1:
a = a.name,
b = b.name;
type = "string";
case 2:
a = a.reputation,
b = b.reputation;
type = "numeric";
// etc
}
if (type == "numeric")
{
// numeric comparison
return a > b ? 1 : (a < b ? -1 : 0);
} else if (type == "string") {
// string comparison
return a.localeCompare(b);
}
// etc
return;
});
localeCompare will compare the strings for you :)

How to "postMessage" to host from within pdf when viewed in IE9 object element

I am attempting to do a small PoC with PDFs and have run into an issue. I am looking to post a message to a PDF and have the PDF post a message to the browser.
The deets:
I am viewing the PDF in an "object" element in IE9. I am using itextsharp to prefill a pdf template on the server, inject some app level javascript (post message and on message stuff) and then serve that up to the browser via a filestreamresult. I am using Reader 10 to view the PDF in IE9.
What works:
So far, everything works except for the PDF posting a message to the browser. I can post a message to the PDF, from the browser, no problem and all of the fields are prefilled as desired.
What doesn't work:
When I try using this.hostContainer.postMessage(["something","somethingmore"]) I get an Acrobat Escript window that says "hostContainer is not defined". I have also tried using "event.target.hostContainer" but I get "event.target is not defined". I am at a loss of what to do and any insight would be super helpful.
Reference links:
Acrobat Javascript API
Stackoverflow How-To on this topic
Original guide I used
The code:
My form view:
<object id="pdfFrame" style="width:100%;height: 100%;" data="#Url.Action("LoadForm")">No luck :(</object>
My custom javascript string method:
private static string GetCustomJavascript(string existingJavaScript)
{
const string newJs =
"this.disclosed = true; " +
"if (this.external && this.hostContainer) { " +
"function onMessageFunc( stringArray ) { " +
// "var name = this.myDoc.getField(personal.name); " +
// "var login = this.myDoc.getField(personal.loginname); " +
"try{" +
"app.alert(doc.xfa);" +
"console.println('Doc xfa value = ' + doc.xfa);" +
// "event.target.hostContainer.postMessage(['hello from pdf!']);" +
// "this.hostContainer.postMessage(['hello from pdf!']);"+
// "name.value = stringArray[0]; " +
// "login.value = stringArray[1]; " +
"} catch(e){ onErrorFunc(e); } " +
"} " +
"function onErrorFunc( e ) { " +
"console.show(); " +
"console.println(e.toString()); " +
"} " +
"try {" +
"if(!this.hostContainer.messageHandler) { " +
"this.hostContainer.messageHandler = new Object(); " +
"this.hostContainer.messageHandler.myDoc = this; " +
"this.hostContainer.messageHandler.onMessage = onMessageFunc; " +
"this.hostContainer.messageHandler.onError = onErrorFunc; " +
"this.hostContainer.messageHandler.onDisclose = function(){ return true; }; " +
"}" +
"} catch(e){onErrorFunc(e);}" +
"}";
var jsToReturn = existingJavaScript + newJs;
return jsToReturn;
}
My method for filling and sending the form to the browser:
public MemoryStream GetFilledRequestForm(string fileDirectory, User user, FormView formView)
{
var pdfStream = new MemoryStream();
var templateFilePath = GetRequestTypeTemplateFilePath(fileDirectory, _requestModule.FormTemplateFileName);
var pdfReader = new PdfReader(templateFilePath);
// pdfReader.RemoveUsageRights();
var stamper = new PdfStamper(pdfReader, pdfStream);
var formFields = GetFormFields(user, formView, pdfReader);
foreach (var field in formFields.Where(f => f.Value != null))
{
stamper.AcroFields.SetField(field.Name, field.Value);
}
stamper.FormFlattening = false;
var newJs = GetCustomJavascript(stamper.Reader.JavaScript);
stamper.AddJavaScript("newJs", newJs);
stamper.Close();
byte[] byteInfo = pdfStream.ToArray();
var outputStream = new MemoryStream();
outputStream.Write(byteInfo, 0, byteInfo.Length);
outputStream.Position = 0;
return outputStream;
}
Ok, so I have resolved it, with some help of course. I found the key at this stack overflow post. I needed to wait for the object to load before assigning the message handler. Additionally, I needed a global variable in the pdf javascript to be able to post the message.
Html/Javascript: (the key here is the loadListener() function)
#model WebModel.FormView
<object id="pdfFrame" style="width:100%;height: 100%;" data="#Url.Action("LoadForm")">No luck :(</object>
<input id="buttonPost" type="button" value="post to pdf"/>
<script type="text/javascript">
var PDFObject = document.getElementById("pdfFrame");
function loadListener() {
if (typeof PDFObject.readyState === 'undefined') { // ready state only works for IE, which is good because we only need to do this for IE because IE sucks in the first place
debugger;
PDFObject.messageHandler = { onMessage: messageFunc };
return;
}
if (PDFObject.readyState == 4) {
debugger;
PDFObject.messageHandler = { onMessage: messageFunc };
} else {
setTimeout(loadListener, 500);
}
}
function messageFunc(data) {
debugger;
var messagedata = data;
alert('finally!!');
}
function sendToPdf() {
if(PDFObject!= null){
PDFObject.postMessage(
["a", "b"]);
}
}
$('#pdfFrame').ready(function() {
loadListener();
$('#buttonPost').on('click', function() {
sendToPdf();
});
});
</script>
My new function to create the javascript: (the key here is var appHostContainer)
private static string GetCustomJavascript(string existingJavaScript)
{
const string newJs =
"this.disclosed = true; " +
"var appHostContainer = this.hostContainer;" +
"if (this.external && this.hostContainer) { " +
"function onMessageFunc( stringArray ) { " +
// "var name = this.myDoc.getField(personal.name); " +
// "var login = this.myDoc.getField(personal.loginname); " +
"try{" +
"app.alert(stringArray);" +
"appHostContainer.postMessage(['hello from pdf!']);" +
// "name.value = stringArray[0]; " +
// "login.value = stringArray[1]; " +
"} catch(e){ onErrorFunc(e); } " +
"} " +
"function onErrorFunc( e ) { " +
"console.show(); " +
"console.println(e.toString()); " +
"} " +
"try {" +
"if(!this.hostContainer.messageHandler) { " +
"this.hostContainer.messageHandler = new Object(); " +
"this.hostContainer.messageHandler.myDoc = this; " +
"this.hostContainer.messageHandler.onMessage = onMessageFunc; " +
"this.hostContainer.messageHandler.onError = onErrorFunc; " +
"this.hostContainer.messageHandler.onDisclose = function(){ return true; }; " +
"}" +
"} catch(e){onErrorFunc(e);}" +
"}";
var jsToReturn = existingJavaScript + newJs;
return jsToReturn;
}

How to return a value from WinJS

I am developing an app which consumes a WebService like this
function callWS(filebytes, fpath, filename) { //consumes the webservice
var response;
var data = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ws="http://ws.myCompany.com">\n' +
' <soapenv:Header/>\n' +
' <soapenv:Body>\n' +
' <ws:uploadFileService>\n' +
' <ws:filebytes>' + filebytes + '</ws:filebytes>\n' +
' <ws:fpath>' + fpath + '</ws:fpath>\n' +
' <ws:filename>' + filename + '</ws:filename>\n' +
' </ws:uploadFileService>\n' +
' </soapenv:Body>\n' +
'</soapenv:Envelope>\n';
console.log("XML SOAP: " + data + "\r\n");
var options = {
url: "http://XXX.XXX.XX.XXX:XXXX/FILESERVERWS/services/FILESERVERWS?wsdl",
type: "post",
headers: {
"Content-Type": "text/xml; charset=utf-8",
"SOAPAction": "uploadFileService"
},
data: data
};
WinJS.Promise.timeout(8000, WinJS.xhr(options)).then(
function (request) {
var doc = request.responseXML.documentElement;
var output = doc.getElementsByTagName("uploadFileServiceReturn");
//Windows.UI.Popups.MessageDialog(output[0].textContent, "the XML message").showAsync();
console.log("the XML message: " + output[0].textContent + "\r\n");
result.style.backgroundColor = "#00A000";
response = true;
},
function (error) {
Windows.UI.Popups.MessageDialog(error.status + " : " + error.statusText, "Status").showAsync();
result.style.backgroundColor = "#FF0000";
response = false;
},
function (progress) {
result.innerText = "Ready state is " + progress.readyState;
result.style.backgroundColor = "#0000A0";
}
);
return response;
}
the purpose is to consume the webService and returns a value
on success response = true
on error response = false
because I want to take an action depending if the webService returned a value by doing this
if (callWS(document.getElementById("formfield" + i).value, UID_KEY[7], arrayCaptures[i - 1].name)) {
console.log("take action a");
}
else {
console.log("take action b");
}
but it always take action B even if the webService is consumed and I get answer from the webservice, what am I doing wrong???
You'll need to return a Promise object from your function, allowing the calling script to use a then() or done() call on it to get the result. You can read more about asynchronous programming in WinJS on the msdn site, but generally it looks like this:
function callWS(filebytes, fpath, filename) {
return new WinJS.Promise(function (complete, error) {
// put your functionality here...
WinJS.Promise.timeout(8000, WinJS.xhr(options)).then(
function (request) {
// more processing...
complete(true); // or false or a variable...
},
function (e) {
// error handling unique to this function
complete(false); // OR you could just call error(e);
},
...
);
});
}
And you would use it like this:
callWS( ... ).then(
function(response) {
// handle response...
// will be either true or false
},
function(err) {
// handle errors
}
);

Categories