Pass a variable to a function from another function in JavaScript (winJs) - javascript

Hi I'am working with Windows 8 app using Java Script
function fetchFromLiveProvider(currentList, globalList,value) {
feedburnerUrl = currentList.url,
feedUrl = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&output=json&num=999&q=" + encodeURIComponent(feedburnerUrl);
WinJS.xhr({url: feedUrl, responseType: "rss/json"
}).done(function complete(result) {
var jsonData = JSON.parse(result.response);
//console.log(JSON.stringify(jsonData));
var entries = jsonData.responseData.feed;
});
}
function setOther(entries){
//some code here
}
I want to do is pass the entries in the fetchFromLiveProvider function to another function called setOther(entries){}. Thank you for any help...

Since WinJS.xhr returns a promise, you can do the following:
var entriesPromise = function fetchFromLiveProvider(currentList, globalList, value) {
feedburnerUrl = currentList.url,
feedUrl = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&output=json&num=999&q=" + encodeURIComponent(feedburnerUrl);
return WinJS.xhr({
url: feedUrl,
responseType: "rss/json"
});
}
function setOther(entries) {
entries.done(function complete(result) {
var jsonData = JSON.parse(result.response);
//console.log(JSON.stringify(jsonData));
var entries = jsonData.responseData.feed;
//some code here
})
}
setOther(entriesPromise);

Related

Cannot get DOT NET CORE MVC to return multiple LINQ results to a view

I am able to pass one value from the controller method, see first cal query to return just the calorie value from the SQL LINQ query. However, I cannot get two colums, see my code controller code and javascript in the view below (I cannot work out what is causing zero data to be populated
I can see var mytext in javascript code return : {"foodCal":101,"foodVarient":"Vegan"}
public JsonResult GetCalories(string Productdata)
{
//THis is the orginal code which returns one value, CALORIES
//var calquery = (from c in _context.Foods
// where c.FoodName == Productdata
// select c.FoodCal).FirstOrDefault();
var calquery = (from c in _context.Foods
where c.FoodName == Productdata
select new
{ c.FoodCal, c.FoodVarient }
).FirstOrDefault();
if (calquery != null)
{
return Json(calquery);
}
else
{
calquery = null;
return Json(calquery);
}
}
<script src="/lib/jquery/dist/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function ()
{
document.getElementById("FoodType").onchange = function ()
{
$.ajax({
type: 'POST',
dataType: 'json',
url: '#Url.Action("GetCalories")',
data: { Productdata: document.getElementById("FoodType").value },
success: function (data)
{
var mytext = JSON.stringify(data);
alert(mytext);
var obj = JSON.parse(json);
document.getElementById("FoodCalories").value = obj.foodCal;
document.getElementById("FoodHealth").value = obj.foodVarient;
}
});
}
});
</script>
I figured out the problem
var object =JSON.parse(mytext), not json
problem solved.
Hope other people benefit from this code.

Function with AJAX run last, how to make it run first

I have one function with AJAX Call(Below Code):
function get_type(Name) {
var field_name;
$.ajax({
type: "GET",
url: "../home/Asset/MR/MR.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('pub').each(function() {
if (Name == $(this).find('pro').text()) {
$(this).find('metadata field').each(function() {
field_name = $(this).find('name').text();
if (field_name == "little") {
type = "L";
} else if (field_name == "Big") {
type = "b";
}
});
}
});
}
});
}
This code works well but the problem is it run after all the functions finished. I want to run this code first I need to get data from the XML. I need to stop the loop of $(xml).find('pub').each(function() this once the Name== $(this).find('pro').text() text is matched. Because this loop execute even I get the answers.
Calling Function codes:
var rd = new FileReader();
rd.onload = function(e) {
var xmlDoc = $.parseXML(this.result);
var $xml = $(xmlDoc);
var J_Name = $xml.find('meta').text();
get_type(J_Name);
//check allowed child of front tag
check_allowed_direct_child("places", "Tirunelveli,Tiruchendur,Alwar", "RULE_002", "Fail");
};
rd.readAsText(this.files[i]);
Callbacks to the rescue!
function get_type(name, cb) {
cb = cb || function () {};
var field_name;
var type;
var types_map = {
'little': 'L',
'Big': 'b'
};
$.ajax({
type: 'GET',
url: '../home/Asset/MR/MR.xml',
dataType: 'xml',
success: function (xml) {
$(xml)
.find('pub')
.each(function () {
if (name == $(this).find('pro').text()) {
$(this)
.find('metadata field')
.each(function () {
field_name = $(this)
.find('name')
.text();
if (types_map.hasOwnProperty(field_name)) {
type = types_map[field_name];
return false; // break out of each()
}
});
return false; // break out of each()
}
});
cb(type); // execute provided callback
}
});
}
var rd = new FileReader();
rd.onload = function (e) {
var xmlDoc = $.parseXML(this.result);
var $xml = $(xmlDoc);
var J_Name = $xml.find('meta').text();
get_type(J_Name, function (type) {
// do stuff once get_type() resolves, type being either matched type or undefined
check_allowed_direct_child('places', 'Tirunelveli,Tiruchendur,Alwar', 'RULE_002', 'Fail');
});
};
rd.readAsText(this.files[i]);
If interested, read on how to make use of Promises, to make callback code a lot more digest: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
If still interested, read on how to use async / await to make Promises code a lot more digest: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

How do I call a method from a class in compiled typescript?

I have created some API helpers in typescript to read/write data from Microsoft Dynamics 2016. I need to call the methods from these helpers in javascript from a page that is interacting with the API. I can't seem to get the code right to call the Get() method from the Web API. What code do I need to put in my $("#ExpenseButton").click callback to call the Get() method?
Javascript Code Compiled from Typescript
var WebAPI;
(function (WebAPI) {
class ExpenseTransaction extends WebAPI.APIBase {
constructor() {
super();
}
ConvertToEntity(data) {
let result = new Array();
for (let i = 0; i < data.length; i++) {
let newRecord = new Model.ExpenseTransaction();
newRecord.ClientID = data[i]["_ccseq_clientid_value"];
newRecord.ClientNumber = data[i]["ccseq_clientnumber"];
newRecord.EmployeeFirstName = data[i]["ccseq_employeefirstname"];
newRecord.EmployeeLastName = data[i]["ccseq_employeelastname"];
newRecord.EmployeeID = data[i]["_ccseq_employeeid_value"];
newRecord.ExpenseErrorCode = data[i]["ccseq_expenseerrorcode"];
newRecord.GeneralLedgerName = data[i]["ccseq_generalledgername"];
newRecord.GeneralLedgerNumber = data[i]["ccseq_generalledgernumber"];
newRecord.GroupCode = data[i]["ccseq_groupcode"];
newRecord.MasterCardPostedDate = data[i]["ccseq_mastercardposteddate"];
newRecord.MasterCardTransactionDate = data[i]["ccseq_mastercardtransactiondate"];
newRecord.MasterCardTransactionParentCompany = data[i]["ccseq_mastercardtransactionparentcompany"];
newRecord.NAVCompanyCode = data[i]["ccseq_navcompanycode"];
newRecord.NAVEmployeeID = data[i]["ccseq_navemployeeid"];
newRecord.NAVGeographyCode = data[i]["ccseq_navgeographycode"];
newRecord.NAVJobClassCode = data[i]["ccseq_navjobclasscode"];
newRecord.NAVServiceCode = data[i]["ccseq_navservicecode"];
newRecord.SetID = data[i]["_ccseq_setid_value"];
newRecord.TransactionAmount = data[i]["ccseq_transactionamount"];
newRecord.TransactionDate = data[i]["ccseq_transactiondate"];
newRecord.TransactionDescription = data[i]["ccseq_transactiondescription"];
newRecord.TransactionType = data[i]["ccseq_transactiontype"];
newRecord.Vendor = data[i]["ccseq_vendor"];
newRecord.StateCode = data[i]["statecode"];
result[i] = newRecord;
}
return result;
}
Get(expenses) {
if (Array.isArray(expenses)) {
if (expenses[0] instanceof Model.ExpenseTransaction) {
return null;
}
}
else {
return Promise.resolve($.ajax({
url: this.Connection,
type: "GET",
contentType: "application/json",
dataType: "json",
}));
}
}
;
Create(expenses) {
for (let i = 0; i < expenses.length; i++) {
$.ajax({
url: this.Connection,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(expenses[i].toJSON()),
success: function (data) {
alert("Success");
},
error: function (data) {
alert("error");
}
});
}
}
;
}
WebAPI.ExpenseTransaction = ExpenseTransaction;
})(WebAPI || (WebAPI = {}));
Javascript Code for Page
(WebAPI || (WebAPI = {}));
$(document).ready(function () {
setupHandlers();
});
function setupHandlers() {
"use strict";
$("#ExpenseButton").click(function () {
// Put Code here
});
}
Code I have Already Tried
// Error: Uncaught TypeError: WebAPI.ExpenseTransaction is not a constructor
let ex = new WebAPI.ExpenseTransaction();
// Error: Uncaught ReferenceError: ExpenseTransaction is not defined
let ex = new ExpenseTransaction();
I think you have to create an instance of the ExpenseTransaction class.
Could you try something like:
function setupHandlers() {
"use strict";
$("#ExpenseButton").click(function () {
var expenseTransaction = new WebAPI.ExpenseTransaction();
var expenses = null;
expenseTransaction.Get(expenses).then(function() {
alert('hello world');
});
});
}
It seems that you are not self-invoking the function that add the class to the WebAPI.
Could you try something like:
(function(WebAPI) {
// YOUR TYPESCRIPT CODE
})(); <-- Invoke the anonymous function
You must have something wrong with your WebAPI object. I have created a simplified version of your code here and it works.
https://jsfiddle.net/jruizx/aru02gja/

Fill array by multiple AJAX requests, then pass array to another function

(My solution below)
I have several HTML elements with class .canvas-background of which information is stored in the database. I want to get the information of each element and process it via JavaScript. But somehow I can't pass the response of the AJAX request to another function. Here is what I've tried:
function initTabs() {
var tabs = loadTabInformation();
console.log(tabs); // (1)
// do something else
}
function loadTabInformation() {
var requests = new Array();
var tabs = new Object();
var counter = 0;
$(".canvas-background").each(function () {
var tabNumber = $(this).data("tab-number");
var request = $.ajax({
type: 'POST',
url: '../db/GetTabInformation.ashx',
data: String(tabNumber),
dataType: 'json',
contentType: 'text/plain; charset-utf-8'
})
.done(function (response) {
tabs[counter++] = response;
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log("request error in loadTabInformation()");
console.log(textStatus);
console.log(errorThrown);
});
requests.push(request);
});
$.when.apply($, requests).done(function () {
console.log(tabs); // (2)
return tabs;
});
}
At (1) I get undefined, but at (2) everything seems to be alright.
THE SOLUTION:
Thanks to the answer and the link in the comment #Kim Hoang provided I got this working. The clue seemed to put the done() function in the calling function, that is initTabs() in my case. Another thing I got wrong was to try to do the logic that should be executed after the AJAX requests had finished outside the done callback function. They must be inside (makes sense, if you think about it). And a lot of conosle output helped, to see what function returns what kind of object.
function initTabs() {
var tabInfoRequest = loadTabInfo();
tabInfoRequest[0].done(function() {
var results = (tabInfoRequest[1].length > 1) ? $.map(arguments, function(a) { return a[0]; }) : [arguments[0]];
for (var i = 0; i < results.length; i++) {
// do something with results[i]
}
});
}
function loadTabInfo() {
var tabNumbers = new Array();
$(".canvas-background").each(function () {
tabNumbers.push($(this).data("tab-number"));
});
var requests = $.map(tabNumbers, function (current) {
return $.ajax({
type: 'POST',
url: '../db/GetTabInformation.ashx',
data: String(current),
dataType: 'json',
contentType: 'text/plain; charset-utf-8'
});
});
var resultObject = new Object();
resultObject[0] = $.when.apply($, requests);
resultObject[1] = requests;
return resultObject;
}
Note: I only did the resultObject-thing because I needed the array requests in the initTabs() function.
Thank you very much for helping me!
You do not return anything in loadTabInformation, so of course you will get undefined. You should do it like this:
function loadTabInformation() {
...
return $.when.apply($, requests);
}
function initTabs() {
loadTabInformation().done(function (tabs) {
console.log(tabs); // (1)
// do something else
});
}

Use Parse Query in then() when using Cloud Code

I can’t seem to get this simple Parse query to work in my cloud code then() it works outside of this but when i place the code inside of this then function nothing happens. The variables are just placeholders for now in terms of testing but i have the default TestObject class you get when you start Parse from the beginning but for some reason it just keeps on returning nothing.
Here is the full function that i am currently using.
// Function which will get the data from all the links passed into the function
Parse.Cloud.define("myNews", function (request, response) {
var promises = _.map(import_io_keys, function (news_api_key) {
return Parse.Cloud.httpRequest({
method: 'GET',
url: "https://api.import.io/store/connector/" + news_api_key + "/_query?input=webpage/url:https%3A%2F%2Fwww.designernews.co%2Fnew&&_apikey=xxxxxxxxxxxxxxxxxx",
headers: {
'Content-Type': 'application/json;charset=utf-8'
}
}).then(function (httpResponse) {
result = JSON.parse(httpResponse.text);
var success = false;
var news_icon = "";
var news_source_name = "";
var query = new Parse.Query("TestObject");
query.find({
success: function(results) {
success = true;
news_icon = results[0].get("foo");
news_source_name = results[0].get("foo");
response.success("done" + news_icon);
},
error: function() {
success = false;
response.error("Query lookup failed");
}
});
for (var story in result.results) {
if(story.length > 0){
if (story["article_link/_text"] !== "" && story["article_link"] !== "" && story["article_time"] !== "") {
if(success){
// Do the stuff later
}
}
}
}
});
});
Parse.Promise.when(promises).then(function () {
console.log("Got all the stories");
response.success(newsJsonData);
}, function () {
response.error("No stories");
console.log("API KEY IS: " + request.params.keys);
});
});

Categories

Resources