I downloaded the code from Git and here is the link https://github.com/MikeWasson/LocalAccountsApp
In this visual studio solution we have JavaScript file called app.js which has the following code.
function ViewModel() {
var self = this;
var tokenKey = 'accessToken';
self.result = ko.observable();
self.user = ko.observable();
self.registerEmail = ko.observable();
self.registerPassword = ko.observable();
self.registerPassword2 = ko.observable();
self.loginEmail = ko.observable();
self.loginPassword = ko.observable();
function showError(jqXHR) {
self.result(jqXHR.status + ': ' + jqXHR.statusText);
//self.loginPassword();
}
self.callApi = function () {
self.result('');
var token = sessionStorage.getItem(tokenKey);
var headers = {};
if (token) {
headers.Authorization = 'Bearer ' + token;
}
$.ajax({
type: 'GET',
url: '/api/values',
headers: headers
}).done(function (data) {
self.result(data);
}).fail(showError);
}
self.register = function () {
self.result('');
var data = {
Email: self.registerEmail(),
Password: self.registerPassword(),
ConfirmPassword: self.registerPassword2()
};
$.ajax({
type: 'POST',
url: '/api/Account/Register',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data)
}).done(function (data) {
self.result("Done!");
}).fail(showError);
}
self.login = function () {
self.result('');
var loginData = {
grant_type: 'password',
username: self.loginEmail(),
password: self.loginPassword()
};
$.ajax({
type: 'POST',
url: '/Token',
data: loginData
}).done(function (data) {
self.user(data.userName);
// Cache the access token in session storage.
sessionStorage.setItem(tokenKey, data.access_token);
}).fail(showError);
}
self.logout = function () {
self.user('');
sessionStorage.removeItem(tokenKey)
}
}
var app = new ViewModel();
ko.applyBindings(app);
What I'm not able to understand that how come properties like
self.result, self.registerEmail, self.registerPassword/Password2, self.loginEmail, self.loginPassword
became methods. Because when I type "self" followed by a dot the intellisense gives all the above mentioned "self" properties as methods. Like
self.result(), self.registerPassword()
And obviously "ko" comes from Knockout.js library.
But when I try to imitate the same in my simple JavaScript code. It fails and I know it's not right to do it here
var SomeObj = {
ok : function()
{
var x = 10, y= 10, z;
z = x+ y;
return z;
}
}
function ViewModel()
{
var self = this;
self.result = SomeObj.ok();
function xyz()
{
self.result();
alert(5700);
}
}
var v = new ViewModel();
alert(v.result());
But how come object "self" has declared "result" as property and used it later like a method in app.js where as when I try
alert(v.result());
in the alert statement It gives me an exception but if I do
alert(self.result());
in app.js it gives me back "undefined" but why not an exception the way I get in my code.
The problem you're seeing here is that by using the parenthesis, you're invoking the SomeObj.ok method, rather than assigning it as a function. To store the method as a function pointer you should do the following:
self.result = SomeObj.ok;
Following this you'll be able to use self.result() to execute the assigned method which will return the result of the assigned SomeObj.ok method.
Check the definition of observable here:
It defines a function which returns a function, which also provides logic for reads and writes based on whether a parameter is sent. If your ok function returned a function, rather than the result, you could access it the same way as observable.
var SomeObj = {
ok : function() {
return function() {
var x = 10, y= 10, z;
z = x+ y;
return z;
}
}
}
Now, the assignment self.result = SomeObj.ok(); would prime self.result with a function, and as such calling self.result() will invoke the function assigned.
Related
i'm really struggling to understand the asynchronous side of JavaScript. the code i have is meant to collate specific details of certain users and then put all the collated information into a global variable array which i intent to manipulate when all the users have been added to the array. i'm finding it difficult to iterate the array because when i do an array.length on the printurlonPage() function i get a 0 despite the fact that when i do a console log on the array itself i can see that there are items there. Does anyone know a technique that allows me to work on the global variable only after the asynchronous function has completed?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
var PeopleCompleteList = [];
function PersonConstructor(username,Title,Phone,Email,imageurl){
return {
name: username,
Title: Title,
phoneNumber: Phone,
Email: Email,
Picture: imageurl
}
}
var printurlonPage = function (){
for (var link in PeopleCompleteList) {
console.log(link['Picture']);
}
console.log(PeopleCompleteList);
}
var getIndividualPersonDetails = function(GetPictureUrl) {
listName = 'TeamInfo';
//var PeopleCompleteList = [];
// execute AJAX request
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('"+listName+"')/items?$select=Name/Title,Name/Name,Name/Id,Name/EMail,Name/WorkPhone&$expand=Name/Id",
type: "GET",
headers: { "ACCEPT": "application/json;odata=verbose" },
success: function (data) {
for (i=0; i< data.d.results.length; i++) {
//check if the user exists if he does store the following properties name,title,workphone,email and picture url
if(data.d.results[i]['Name'] != null){
var personName = data.d.results[i]['Name'].Name.split('|')[2];
var userName = data.d.results[i]['Name']['Name'];
var UserTitle = data.d.results[i]['Name']['Title'];
var UserphoneNumber = data.d.results[i]['Name']['WorkPhone'];
var UserEmail = data.d.results[i]['Name']['EMail'];
var myuserPicture = GetPictureUrl(userName);
console.log(myuserPicture);
PeopleCompleteList.push(PersonConstructor(personName, UserTitle, UserphoneNumber,UserEmail,myuserPicture));
}
}
},
error: function () {
alert("Failed to get details");
}
});
}
function GetPictureUrl(user) {
var userPicture="";
var requestUri = _spPageContextInfo.webAbsoluteUrl +
"/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=#v)?#v='"+encodeURIComponent(user)+"'";
$.ajax({
url: requestUri,
type: "GET",
async:false,
headers: { "ACCEPT": "application/json;odata=verbose" },
success: function (data) {
console.log(data);
var PictureDetails = data.d.PictureUrl != null ? data.d.PictureUrl : 'c:\apps\noimageurl.jpg';
userPicture=PictureDetails;
}
});
return userPicture;
};
$(function () {
getIndividualPersonDetails(GetPictureUrl);
printurlonPage();
});
</script>
You're printurlonPage() is not asynchronous, so it's running before getIndividualPersonDetails responds. You can do two things, use promises or use async/await from es7. I prefer async/await, but you'll need to babelify.
Or, you can just put your printurlonPage invocation inside your success: handler.
success: function (data) {
for (i=0; i< data.d.results.length; i++) {
//check if the user exists if he does store the following properties name,title,workphone,email and picture url
if(data.d.results[i]['Name'] != null){
var personName = data.d.results[i]['Name'].Name.split('|')[2];
var userName = data.d.results[i]['Name']['Name'];
var UserTitle = data.d.results[i]['Name']['Title'];
var UserphoneNumber = data.d.results[i]['Name']['WorkPhone'];
var UserEmail = data.d.results[i]['Name']['EMail'];
var myuserPicture = GetPictureUrl(userName);
console.log(myuserPicture);
PeopleCompleteList.push(PersonConstructor(personName, UserTitle, UserphoneNumber,UserEmail,myuserPicture));
}
}
printurlonPage();
},
And then in document.ready:
$(function () {
getIndividualPersonDetails(GetPictureUrl);
});
So, getIndividualPersonDetails is invoked, and then when it receives the data, the callback is invoked with the data.
I have a Asp.net MVC program in which i want to get a list from the View using Javascript and pass that list to the controller. I want to the variables in the list to be string type except for one to be int32.
The problem is the list is either empty or does not pass.
I tried to use stringify but it doesn't fill the requirments.
Here is the code from the javascript part:
$('#AddColumn').click(function () {
var nodeURL = document.getElementById("IDHolder").innerHTML;
var nodeConfig= nodeURL+".CONFIG";
var nodeAdd=nodeURL+".CONFIG.AddColumn";
var nodeName = $("#ColumnName").val();
var nodeType = $("#ColumnType").data("kendoComboBox").value();
var ListNodedet = [nodeName, nodeType];
var Listmet = [nodeConfig, nodeAdd];
var ListNodeDetails = JSON.stringify(ListNodedet);
var ListMethod = JSON.stringify(Listmet);
var select = 1;
var url = "/Configuration/CallMethod";
$.get(url, { ListNodeDetails:ListNodeDetails, ListMethod:ListMethod }, function (data) {
$("#Data2").html(data);
});
})
The C# code for the controller were it calls another method in models:
public bool CallMethod(List<Variant> ListNodeDetails, List <string> ListMethod)
{
var AddMethod = RxMUaClient.CallMethod(ListNodeDetails, ListMethod, "127.0.0.1:48030");
return AddMethod;
}
The Model:
public static bool CallMethod(List<Variant> ListNodeDetails, List<string> ListMethod, string iPAddress)
{
var serverInstance = GetServerInstance(iPAddress);
if (serverInstance == null)
return false;
return serverInstance.CallMethod(ListNodeDetails, ListMethod);
}
The service model
public bool CallMethod(List<Variant> ListNodeDetails, List<string> ListMethod)
{
try
{
if (_mSession == null)
{
return false;
}
NodeId objectID = NodeId.Parse(ListMethod[0]);
NodeId Methodtype = NodeId.Parse(ListMethod[1]); ;
List<Variant> inputArguments = ListNodeDetails;
List<StatusCode> inputArgumentErrors = null;
List<Variant> outputArguments = null;
StatusCode error = _mSession.Call(
objectID,
Methodtype,
inputArguments,
new RequestSettings() { OperationTimeout = 10000 },
out inputArgumentErrors,
out outputArguments);
if (StatusCode.IsBad(error))
{
Console.Write("Server returned an error while calling method: " + error.ToString());
return false;
}
return true;
}
catch (Exception exception)
{
Console.WriteLine(exception.ToString());
return false;
}
}
At the end it calls some functions using OPC UA to add data.
I have changed it to be ajax function and it works well but only with one list form the lists passed to the method!
I dont know if this is because i read values from kendo box and text box, and they are different types but i tried to stringfy it and it still does not work. On the console both lists are out as strings. So still got a problem with passing the first List "ListNodeDetails"!
$('#AddColumn').click(function () {
var nodeURL = document.getElementById("IDHolder").innerHTML;
var nodeConfig= nodeURL+".CONFIG";
var nodeAdd=nodeURL+".CONFIG.AddColumn";
var nodeName = $("#ColumnName").val().toString();
var nodeType = $("#ColumnType").data("kendoComboBox").value().toString();
var ListNodedet = [nodeName, nodeType];
var Listmet = [nodeConfig, nodeAdd];
var params = {
ListNodeDetails: ListNodedet,
ListMethod: Listmet
};
var url = "/Configuration/CallMethod";
console.log(params); // added sanity check to make sure data is correctly passed
var temp = {
url: "/Configuration/CallMethod",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(params),
success: function (params) {
window.location.replace(params.redirect);
}
};
$.ajax(temp);
})
I'm trying to read p_info array returned from the function getproductInfo containing a ajax call but I'm getting undefined value. I'm using a callback function to achieve this but still doesn't work. Where am I wrong?
$(document).ready(function() {
function successCallback(data)
{
var name = data.name;
var image = data.image;
var link = data.link;
var product_info = [name, image, link];
console.log(product_info); // Correct: shows my product_info array
return product_info;
}
function getProductInfo(prodId, successCallback) {
$.ajax({
type: "POST",
url: "getProductInfo.php",
data: "id=" + prodId,
dataType: "json",
success: function(data) {
var p_info = successCallback(data);
console.log(p_info); // Correct: shows my product_info array
return p_info;
},
error: function()
{
alert("Error getProductInfo()...");
}
});
return p_info; // Wrong: shows "undefined" value
}
var p_info = getProductInfo(12, successCallback);
console.log(p_info); // Wrong: shows an empty value
});
The code should speak for itself. But basically, you cant return an upper-level function inside a function. You must set a variable to be used to return after the ajax is submitted.
//This makes the p_info global scope. So entire DOM (all functions) can use it.
var p_info = '';
//same as you did before
function successCallback(data) {
var name = data.name;
var image = data.image;
var link = data.link;
var product_info = [name, image, link];
return product_info;
}
//This takes prodID and returns the data.
function getProductInfo(prodId) {
//sets up the link with the data allready in it.
var link = 'getProductInfo.php?id=' + prodId;
//creates a temp variable above the scope of the ajax
var temp = '';
//uses shorthand ajax call
$.post(link, function (data) {
//sets the temp variable to the data
temp = successCallback(data);
});
//returns the data outside the scope of the .post
return temp;
}
//calls on initiates.
var p_info = getProductInfo(12);
console.log(p_info);
I asked a question to fill in the model data on the client, into arrays.
Add items to JSON objects
Now my problem is how to post it to the controller. I have tried this:
public ActionResult ItemRequest (Model1 model)
{
////
}
but it never gets there.
I'm trying with an AJAX request to send it:
function sendRequest() {
jsonData.items = itemArray;
$.ajax({
url: '#Url.Action("ItemRequest")',
type: 'POST',
data: JSON.stringify(jsonData),
///// and so on
}
But the action result is never invoked. I can drop the 'JSON.stringify' and it makes no difference. Any ideas on how to post this object to the controller?
If I make a psuedo model in JS it works fine, but I don't want to have to make this model, I'd rather use the model passed to the page.
function itemModel () {
var self = this;
this.itemNumber = $("#itemNumberId").val();
/// etc.
self.items = [];
}
function itemsModel () {
var self = this;
this.itemNumber = $("#itemNumberId").val();
/// etc
}
then
var itemCount = 0;
function addItem() {
var newItem = new itemModel();
newItem.items[itemCount] = newItem;
/// etc
}
This works fine.
I send the array itemModel the same way with a JSON.stringify directly into the controller method
public ActionResult ItemRequest(ItemModel model)
We are using this to send Data to API controller Methods on our internal test sides:
It's probably not the prettiest solution, but it can be used on any page.
What data should be sent:
$("#btnSend").click(function () {call("controller/method", {ParamName: $("#field").val()}); });
To send the data to a controller:
$(document).ready(function () {
var call = function (method, requestData, resultHandler) {
var url = method.substring(0, 1) == "/api/" + method;
$.ajax({
url: url,
dataType: 'json',
data: JSON.stringify(requestData),
type: 'POST',
contentType: 'application/json',
success: function (data) {
var isSuccess = data.Status == "success";
$("#jsonResponse").val(FormatJSON(data));
if (isSuccess && jQuery.isFunction(resultHandler)) {
resultHandler(data);
}
}
});
};
I have a "class"/function called Spotlight. I'm trying to retrieve some information through ajax and assign it to a property of Spotlight. Here is my Spotlight class:
function Spotlight (mId,mName) {
this.area = new Array();
/**
* Get all area information
*/
this.getArea = function () {
$.ajax({
url: base_url +'spotlight/aGetArea',
type: 'POST',
success: function (data) {
this.area = data;
}
});
}
}
I have assigned the object to an array, and it would be difficult to get to it from within Spotlight, so I'm hoping to access everything using 'this.' It appears though that the success function is outside of the class, and I don't know how to make it inside the class.
Is there a way to get the data into the class property using this.area rather than Spotlight.area?
The value of this is dependent on how each function is called. I see 3 ways around this problem:
1. Creating an alias to this
var that = this;
this.getArea = function () {
$.ajax({
url: base_url +'spotlight/aGetArea',
type: 'POST',
success: function (data) {
that.area = data;
}
});
};
2. Using jQuery .ajax context option
this.getArea = function () {
$.ajax({
url: base_url +'spotlight/aGetArea',
type: 'POST',
context : this,
success: function (data) {
this.area = data;
}
});
};
3. Using a bound function as the callback
this.getAreaSuccess = function (data) {
this.area = data;
};
this.getArea = function () {
$.ajax({
url: base_url +'spotlight/aGetArea',
type: 'POST',
success: this.getAreaSuccess.bind(this)
});
};
Well Spotlight.area wouldn't work anyway. You just need to preserve the outer this:
this.area = [];
var theSpotlight = this;
and then in the callback:
theSpotlight.area = data;
When inside the success function, this corresponds to the scope of the success function.
function Spotlight (mId,mName) {
this.area = [];
var scope = this;
/**
* Get all area information
*/
this.getArea = function () {
$.ajax({
url: base_url +'spotlight/aGetArea',
type: 'POST',
success: function (data) {
scope.area = data;
}
});
}
}