putting condition on self.load function in knockout - javascript

This is my view model:
function viewModel() {
var self = this;
self.posts = ko.observableArray();
self.newMessage = ko.observable();
self.error = ko.observable();
and these are my two loads functions:
self.reloadPosts = function () {
$.ajax({
type: "Get",
url: postApiUrl2,
data: { id: $("#Locations").val() },
datatype: "json",
contentType: "application/json"
})
}
self.loadPosts = function () {
// to load existing posts
$.ajax({
url: postApiUrl1,
// data: { id: $("#Locations").val() },
datatype: "json",
contentType: "application/json",
cache: false,
type: 'Get'
})
}
self.loadPosts();
self.reloadPosts();
return self;
here, self.loadPosts is the function with no parameter in it and self.reloadPosts passes selected dropdown id to controller.
My question is-- is it possible to put condition here so that self.reloadPosts should only load data on the view page when it has some data.
Right now, both of these are loading one by one. i want to control it by some condition.this code is in .js file not on .cshtml page.
I am trying something like this but getting uncaught reference errror at first line:
if (id != null) {
self.reloadPosts();
}
else {
self.loadPosts();
}
Can anyone suggest me something how to do it.

I don't know what #locations refers to, but if it's a select list or something try this in the HTML (for example):
<select data-bind="value: locations">
<option>location 1</option>
<option>location 2</option>
<select>
And change the script:
function viewModel() {
var self = this;
// location will be stored here
self.locations = ko.observable();
self.posts = ko.observableArray();
self.newMessage = ko.observable();
self.error = ko.observable();
// we can avoid some repeat code:
self.loadPosts = function () {
// read value
var id = self.locations();
// set url and data
var url = (id) ? postApiUrl2 : postApiUrl1;
var data = (id) ? { id: id } : null;
$.ajax({
type: "Get",
url: url,
data: data,
datatype: "json",
contentType: "application/json"
})
}
self.loadPosts();
return self;
Hope this helps.

Related

Passing A Single Objects Into An MVC Controller Method Using jQuery Ajax

I'm trying to post a single object data to an MVC Controler using JQuery, Below are my codes.
//declare of type Object of GroupData
var GroupData = {};
//pass each data into the object
GroupData.groupName = $('#groupName').val();
GroupData.narration = $('#narration').val();
GroupData.investmentCode = $('#investmentCode').val();
GroupData.isNew = isNewItem;
//send to server
$.ajax({
url: "/Admin/SaveContributionInvestGroup",
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
data: JSON.stringify({ GroupData: JSON.stringify(GroupData) }),
success: function (res) {
alertSuccess("Success", res.Message);
//hide modal
$('#product-options').modal('hide');
hide_waiting();
},
error: function (res) {
alertError("Error", res.Message);
}
});
Below is my controller.
[HttpPost]
public JsonResult SaveContributionInvestGroup(ContributionInvestmentGroup GroupData)
{
ClsResponse response = new ClsResponse();
ClsContributionInvestmentGroup clsClsContributionInvestmentGroup = new ClsContributionInvestmentGroup();
var userID = (int)Session["userID"];
var sessionID = (Session["sessionID"]).ToString();
if (contributionGroupData != null)
{
//get the data from the cient that was passed
ContributionInvestmentGroup objData = new ContributionInvestmentGroup()
{
contributionInvestmentGroupID = 0,
groupName = GroupData.groupName,
narration = GroupData.narration,
investmentCode = GroupData.investmentCode,
isNew = GroupData.isNew
};
response = clsClsContributionInvestmentGroup.initiateNewContributionInvestmentGroup(sessionID, objData);
}
else
{
response.IsException = true;
response.IsSucess = false;
response.Message = "A system exception occurred kindly contact your Administrator.";
}
return Json(new
{
response.IsSucess,
response.Message
});
}
The issue is, the data is not been posted to the controller, the controller receives a null object.
Kindly assist, would really appreciate your effort, thanks.
Try Like this:
//send to server
$.ajax({
type: "POST",
url: "/Admin/SaveContributionInvestGroup",
dataType: "json",
data: GroupData,
success: function (res) {
alertSuccess("Success", res.Message);
//hide modal
$('#product-options').modal('hide');
hide_waiting();
},
error: function (res) {
alertError("Error", res.Message);
}
});
in your controller your dont have custom binding to bind JSON to your model thats why you get null in you parameter.
instead just post it as query, try simply changes your ajax option like so:
{
...
contentType: "application/x-www-form-urlencoded", //default:
...,
data: $.param(GroupData),
...
}
and perhaps property names are case sensitive so you will need to change your javascript model's name

how i can prevent reload sub folder of same parent FuelUX Tree

var DataSourceTree = function (options) {
this.url = options.url;
}
DataSourceTree.prototype = {
data: function (options, callback) {
var self = this;
var $data = null;
var param = null
if (!("name" in options) && !("type" in options)) {
param = 0; //load the first level
} else if ("type" in options && options.type == "folder") {
if ("additionalParameters" in options && "children" in options.additionalParameters) {
param = options.additionalParameters["id"];
}
}
if (param != null) {
$.ajax({
url: this.url,
data: 'id=' + param,
type: 'POST',
dataType: 'json',
success: function (response) {
callback(response)
},
error: function (response) {
console.log(response);
}
})
}
}
};
$('#tree2').admin_tree({
dataSource: new DataSourceTree({ url: 'AccountTree.ashx' }),
loadingHTML: '<div class="tree-loading"><i class="fa fa-spinner fa-2x fa-spin"></i></div>',
'open-icon': 'fa-folder-open',
'close-icon': 'fa-folder',
'selectable': false,
'multiSelect': false,
'selected-icon': null,
'unselected-icon': null
});
this JSON data i revived from AccountTree.ashx
{\"data\":[{\"id\":1,\"name\":\"label 1\",\"type\":\"folder\",\"additionalParameters\":{\"id\":1,\"children\":true,\"itemSelected\":false,\"name\":\"test\",\"type\":\"item\"}}]}
i know there is something wrong in callback(response)
http://i.stack.imgur.com/6DEtr.png
must be label1 --> item
It seems that your data source function is not changing the URL you are getting JSON from.
When a folder node is opened it uses whatever JSON the datasource gives it. Use the attr key and the event opened.fu.tree to give your nodes data attributes that will then inform/manipulate your datasource and tell it what URL and thus JSON to load.

Jquery Ajax called 'click' called on an object that does not implement interface HTMLElement

I have the following javascript:
$('#edit_category').on('click','#btn_save_category_name',function(){
currently_edit.text($('#txt_edit_category').val());
edit_category_name(currently_edit,current_category_id);
$('#edit_category').modal('hide')
})
function edit_category_name(name, id){
$.ajax({
type: 'POST',
url: '/Category/edit_team_category',
dataType: 'json',
data: {
request: 'ajax',
name: name,
id: id
},
success: function (data) {
}
});
}
Now when i attempt this i get the following error: called 'click' called on an object that does not implement interface HTMLElement.
But if i comment the function line out aka : edit_category_name(currently_edit,current_category_id);
everything works fine.
Can anyone tell me why this is happening?
Update my full script
var mode = 'team';
var currently_edit = '';
var current_team_id = 0;
var current_category_id = 0;
jQuery(document).ready(function(){
//Main click function for Team (selection of team)
$('#team_wrapper').on('click', '.panel-heading', function () {
if(mode === 'team'){
current_team_id = $(this).siblings('small').text()
title = $(this).find('.text-white').text();
var i = 100;
$('#span_search').hide();
$('#btn_new_team').fadeOut();
$('.col-lg-3').each(function(){
$('.alt').toggle('slow');
$(this).fadeOut(300,function(){
$(this).remove();
});
});
$('#team_title').text('Select Category');
$('#btn_new_category').delay(500).fadeIn();
$('#selected_team_name').text(title);
$('#selected').delay(695).fadeIn();
$('#span_search').delay(500).fadeIn();
$('#back').delay(500).fadeIn();
generate_categories();
mode = 'category';
}else{
$(this).next('div').find('a')[0].click();
}
})
$('#team_wrapper').on('click', '.btn_administrate', function(){
current_team_id = $(this).next('.team_id').text();
load_team_members(current_team_id);
});
//Modal category:
//create
$('#btn_create_category').click(function(){
add_category($('#txt_create_category').val());
$('#group-form').modal('hide');
$('#txt_create_category').val('');
})
// edit
$('#team_wrapper').on('click','.team_category_edit',function(){
current_category_id= $(this).next('input').val()
edit_mode('txt_edit_category',$(this).closest("div").prev().find("h3"));
})
$('#edit_category').on('click','#btn_save_category_name',function(){
currently_edit.text($('#txt_edit_category').val());
edit_category_name(currently_edit,current_category_id);
$('#edit_category').modal('hide')
})
});
function edit_category_name(name, id){
$.ajax({
type: 'POST',
url: '/Category/edit_team_category',
dataType: 'json',
data: {
request: 'ajax',
name: name,
id: id
},
success: function (data) {
}
});
}
in this example:
var current_team_id = 1;
var current_category_id = 2;
What is the value of currently_edit? I am assuming this is a jQuery object not a text value. Try the following instead.
edit_category_name(currently_edit.text(),current_category_id);
Update
As Barmar mentioned, currently_edit.text(...) is invalid based on what you have shared. perhaps what you meant to do was:
currently_edit = $('#txt_edit_category').val();
Try changing this line currently_edit.text($('#txt_edit_category').val());
with this : currently_edit = $('#txt_edit_category').val();

how to bind selectlist to value using json in javascript

I'm new to web application development and i need to bind values which i retrieved from json object. i tried several ways but couldn't able to bind values to my combo box.
<script type="text/javascript">
var ViewModel = {
CheckIn : ko.observable(),
CheckOut: ko.observable(),
Lunch: ko.observable(),
Rest: ko.observable(),
WorkOnProject: ko.observable(),
Projects: ko.observableArray()
};
this.GetProjects = function () {
$.ajax({
type: "POST",
url: 'TimeRecord.aspx/ReturnComplexType',
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (arg) {
for (var i = 0; i < arg.d.length ; i++) {
var value = arg.d[i].ProjectCode;
var option = new Option(arg.d[i].ProjectCode, arg.d[i].ProjectCode);
Select1.add(option, null);
}
},
error: function (arg) {
}
});
};
ko.applyBindings(ViewModel);
</script>
My HTML Code:
<tr>
<td class="auto-style1">Project Code </td>
<td ><select id="Select1" data-bind='options: Projects' style="width: 312px"></select>
<button data-bind='click: GetProjects'>Cancel</button>
</td>
</tr>
My Sever Side Coding :
[WebMethod]
public static object ReturnComplexType()
{
List<Project> projects = new List<Project>();
Project p = new Project();
p.ProjectID = 1;
p.ProjectCode = "ABC";
p.ProjectName = "Test";
projects.Add(p);
Project p2 = new Project();
p2.ProjectID = 2;
p2.ProjectCode = "DEF";
p2.ProjectName = "xsd";
projects.Add(p2);
return projects;
}
Your structure is way off, you're mixing object instances with function on the window object..
This is one way of solving it
ViewModel = function() {
this.CheckIn = ko.observable();
this.CheckOut = ko.observable();
this.Lunch = ko.observable();
this.Rest = ko.observable();
this.WorkOnProject = ko.observable();
this.Projects = ko.observableArray()
};
ViewModel.prototype = {
GetProjects: function () {
$.ajax({
type: "POST",
url: 'TimeRecord.aspx/ReturnComplexType',
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
this.Projects(data);
}.bind(this),
error: function (arg) {
}
});
};
};
ko.applyBindings(new ViewModel());
What I did was to move the GetProjects function to the model object
Your select box is bound to the Projects observable but you don't set an explicit text/value
<select id="Select1" data-bind='options: Projects, optionsText: 'ProjectName', optionsValue:'ProjectID', value: SelectedProjectId"' style="width: 312px"></select>
The SelectedProjectId would be another observable in your model if you need to save the value somewhere.
The other thing you'll want to change is filling the actual observable array instead of select box directly.
<script type="text/javascript">
function ViewModel() {
var self = this;
self.CheckIn = ko.observable();
self.CheckOut = ko.observable();
self.Lunch = ko.observable();
self.Rest = ko.observable();
self.WorkOnProject = ko.observable();
self.Projects = ko.observableArray();
};
var VM = new ViewModel();
ko.applyBindings(ViewModel);
$.ajax({
type: "POST",
url: 'TimeRecord.aspx/ReturnComplexType',
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (arg) {
for (var i = 0; i < arg.d.length ; i++) {
VM.Projects.push(d[i]);
}
},
error: function (arg) {
}
});
</script>
After you get things binding right you'll probably want to swap out the VM.Projects.push() for a speedier way.
Calling .push() when you're filling up arrays on initial load triggers a ton of notifications that can really make the page crawl.

Saving javascript objects using jquery and passing an ID from database

I am using jQuery to save the values of my javascript objects. I need to retreive the ID of inserted object from the database. I know how to do it, if the Save function is within the javascript object (see code below). But how can I set the ID variable, if the Save function is not in the javascript object?
Working:
Person = function() {
var self = this;
self.ID;
self.Name;
self.SurName;
self.Save = function() {
$.ajax({
type: "POST",
url: "Save",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ Name: self.Name, SurnName: self.SurName }),
dataType: "json",
success: function (result) {
var ID = result.d.ID; //this is the ID retreived from database
self.ID = ID; //set the ID, it works, since I can reference to self
}
});
};
}ยจ
So how would I now implement a function (outside the Person class!) like:
SavePerson = function(p) {
$.ajax({
type: "POST",
url: "Save",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ Name: p.Name, SurnName: p.SurName }),
dataType: "json",
success: function (result) {
var ID = result.d.ID; //this is the ID retreived from database
p.ID = ID; //set the ID, it doesn't work, becouse if I call SavePerson repetedly for different objects, a p will not be a correct person.
}
});
};
Just to clarify, you would like the Person object id property to be updated with the recent save? If so the following script would suffice. I have used deferred's to ensure that p.ID is only updated upon completion of the asynchronous request.
$.Person = function() {
var self = this;
self.ID;
self.Name;
self.SurName;
}
$.SavePerson = function() {
var dfd = $.Deferred();
$.ajax({
type: "POST",
url: "Save",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ Name: p.Name, SurnName: p.SurName }),
dataType: "json",
success: dfd.resolve
});
return dfd.promise();
};
var p = new $.Person();
$.SavePerson().then(function(result){
p.ID = result.d.ID;
});
There may be better ways to do this but I'd have my database also return the Name and Surname along with the ID, then search my Person list to find the correct object in the success function.
Perhaps this is what you desire?
I borrowed some code here:
/*** makeClass() ***
* The following allows us to easily create
* Javascript classes. Source of this:
* http://ejohn.org/blog/simple-class-instantiation/
* makeClass - By John Resig (MIT Licensed)
*/
function makeClass() {
return function(args) {
if (this instanceof arguments.callee) {
if (typeof this.init == "function") this.init.apply(this, args.callee ? args : arguments);
} else return new arguments.callee(arguments);
};
});
/* set up ajax */
$.ajaxSetup({
async: false,
type: "POST",
contentType: "application/json",
converters: {
"json jsond": function(msg) {
return msg.hasOwnProperty('d') ? msg.d : msg;
}
},
data: '{}',
dataType: "json",
error: function(jqXHR, status, error) {
alert("An error occurred on the server. Please contact support.");
}
});
/* set up my person class */
var personClass = makeClass();
personClass.prototype.init = function() {
this.ID = '';
this.SurName = '';
this.Name = '';
}
/* create my save function */
personClass.prototype.SavePerson = function(p) {
this.Name = (typeof p === 'undefined') ? this.Name : p.Name;
this.SurName = (typeof p === 'undefined') ? this.SurName : p.SurName;
$.ajax({
url: "Save",
data: JSON.stringify({
Name: this.Name,
SurnName: this.SurName
}),
success: function(result) {
var ID = result.ID; //ID from database
this.ID = ID; //set the ID,
}
});
};
//create two persons
var person1 = personClass();
var person2 = personClass();
//set person1 to be fred
person1.Name = "Fred";
person1.SurName = "Flintstone";
// independent person
var p = {Name: "Barney", SurName: ""};
p.Surname = "Rubble";
//save specific and the independent (as person2)
person1.SavePerson();
person2.SavePerson(p);
//alert the ID of both
alert(person1.ID + ":" + person2.ID);

Categories