How to Move code from jsfiddle to local system for testing - url

This similar to Question https://stackoverflow.com/questions/13693170/changed-version-of-knockout-js
I would like move the code from jsfiddle to local system for testing. The code works for adds, checked, delete. But, what it does not do is load the fake data from within the model.js. I have changed /echo/json. to local url. What else do I need to do? Using latest firefox.
model.js >>>>
$(document).ready(function() {
var fakeData = [{
"title": "Wire the money to Panama",
"isDone": true},
{
"title": "Get hair dye, beard trimmer, dark glasses and passport",
"isDone": false},
{
"title": "Book taxi to airport",
"isDone": false},
{
"title": "Arrange for someone to look after the cat",
"isDone": false}];
function Task(data) {
this.title = ko.observable(data.title);
this.isDone = ko.observable(data.isDone);
}
function TaskListViewModel() {
// Data
var self = this;
self.tasks = ko.observableArray([]);
self.newTaskText = ko.observable();
self.incompleteTasks = ko.computed(function() {
return ko.utils.arrayFilter(self.tasks(), function(task) { return !task.isDone() && !task._destroy });
});
// Operations
self.addTask = function() {
self.tasks.push(new Task({ title: this.newTaskText() }));
self.newTaskText("");
};
self.removeTask = function(task) { self.tasks.destroy(task) };
self.save = function() {
$.ajax("/ds", {
data: {
json: ko.toJSON({
tasks: this.tasks
})
},
type: "POST",
dataType: 'json',
success: function(result) {
alert(ko.toJSON(result))
}
});
};
//Load initial state from server, convert it to Task instances, then populate self.tasks
$.ajax("/ds", {
data: {
json: ko.toJSON(fakeData)
},
type: "POST",
dataType: 'json',
success: function(data) {
var mappedTasks = $.map(data, function(item) {
return new Task(item);
});
self.tasks(mappedTasks);
}
});
}
ko.applyBindings(new TaskListViewModel());
});
ds.html
<script type="text/javascript" src="static/js/jquery-1.6.3.min.js"></script>
<script type="text/javascript" src="static/js/knockout-2.0.0.js"></script>
<p>
<div class="codeRunner">
<h3>Tasks</h3>
<form data-bind="submit: addTask">
Add task: <input data-bind="value: newTaskText" placeholder="What needs to be done?" />
<button type="submit">Add</button>
</form>
<ul data-bind="foreach: tasks, visible: tasks().length > 0">
<li>
<input type="checkbox" data-bind="checked: isDone" />
<input data-bind="value: title, disable: isDone" />
Delete
</li>
</ul>
You have <b data-bind="text: incompleteTasks().length"> </b> incomplete task(s)
<span data-bind="visible: incompleteTasks().length == 0"> - it's beer time!</span>
<button data-bind="click: save">Save</button>
</div>
</p>
<script type="text/javascript" src="static/js/model.js" ></script>

The ajax requests in the fiddle are just mock requests to simulate real-world scenarios, they're not really necessary.. you can use that fake data without any ajax requests. For example change these parts:
self.save = function() {
alert(ko.toJSON({tasks: this.tasks}));
};
//Load initial state from server, convert it to Task instances, then populate self.tasks
var mappedTasks = $.map(fakeData, function(item) {
return new Task(item);
});
self.tasks(mappedTasks);
If you want to use ajax requests to get real data, you'll need to post the data in the format required by your own server API (i.e. not with that 'json' field in the data that is used in jsfiddle's json-echo service API)

Related

Select2 initSelection element Val

I am using the select2 control on my web aplciation. In the initSelection I am passing the element.val() to a controller but it is null. How would I set element.val() that i want pass to the Url.Action. Is element.val() the correct object that I should be using when I am using a div?
I see the value in Chrome
debugger
view
<div id="guideline-container" style="#(Model.Type == "Guideline" ? "display:block" : "display:none")">
<form id="guideline-form" class="form-horizontal">
<div class="form-group">
<label for="guidelineName" class="col-sm-2 control-label">Guideline</label>
<div class="col-sm-10">
<div id="guidelineName">
#{ Html.RenderAction("Index", "GuidelinesPicklist", new { value = Model.GuidelineId, leaveOutAlgorithmItems = true, separateActiveItems = true }); }
</div>
<div class="guideline-not-selected field-validation-error" style="display: none;">
Guideline is required.
</div>
</div>
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary modal-submit-btn">Add</button>
<button type="button" class="btn btn-default modal-close-btn" data-dismiss="modal">Close</button>
</div>
</form>
</div>
function
$(this).select2({
placeholder: "#Model.Settings.Placeholder",
//allowClear: true,
ajax: {
url: "#Url.Action("GetPicklistItems")",
contentType: 'application/json; charset=utf-8',
type: 'POST',
dataType: 'json',
data: function (params) {
return JSON.stringify({
query: params.term,
args: #Html.Raw(JsonConvert.SerializeObject(#Model.Settings != null ? #Model.Settings.AdditionalArguments : null))
});
},
processResults: function (data, page) {
console.log("processResults");
console.log(data);
var resultData = [];
if (isError(data)) {
showErrorMessage(getErrorMessage(data));
} else {
hideErrorMessage();
mapResultData(data.Result, resultData, 0);
}
return {
results: resultData
};
}
},
templateResult: format,
templateSelection: function(data) {
return data.text;
},
initSelection: function (element, callback) {
//console.log("initSelection");
//var id = $(element).val();
//console.log(id);
var guidelineId = "#Model.Value";
console.log("guidelineId");
console.log(guidelineId);
//console.log("params");
//console.log(params);
//console.log("element object Text");
//console.log(element.text);
debugger;
getAjax("#Url.Action("GetPicklistItem")" + "?value=" + guidelineId, function (result)
{
console.log("Ajax GetPicklistItem");
console.log(result);
debugger;
if (result.Result) {
var data = {};
$.extend(data, result.Result);
data.id = result.Result.Value;
data.text = result.Result.Text;
callback(data);
self.trigger("picklistChanged", data);
} else {
console.log(result);
debugger;
callback ({ id: null, text: "#Model.Settings.Placeholder" })
}
});
},
escapeMarkup: function(m) {
return m;
}
}).on('change', function () {
var data = self.select2('data');
self.trigger("picklistChanged", data);
});
You can get Select2 selected value or text by using the following approaches:
var selectedValue = $('#Employee').val();
var selectedText = $('#Employee :selected').text();
Alternatively you can simply listen to the select2:select event to get the selected item:
$("#Employee").on('select2:select', onSelect)
function onSelect(evt) {
console.log($(this).val());
}

I have a Rails app using React posting to my db using an ajax call. How do I handle the redirect?

So I have my Rails app trying to submit a cohort to the database. I can get it to post to the database but I do not know how to handle the redirect.
var NewCohort = React.createClass ({
getInitialState: function() {
return {name:'',description:''}
},
handleNameChange: function(e) {
this.setState({name:e.target.value})
},
handleDescriptionChange: function(e) {
this.setState({description:e.target.value})
},
handleSubmit: function(e) {
var that = this
$.ajax({
url: '/cohorts',
method: 'POST',
data: {
name: that.state.name,
description: that.state.description
},
success: function(data, success, xhr) {
console.log(data)
}
})
},
render: function() {
return (
<div className="container">
<h3>Create a new cohort</h3>
<form onSubmit={this.handleSubmit}>
<input type="text" value={this.state.name} onChange={this.handleNameChange}/>
<input type="text" value={this.state.description} onChange={this.handleDescriptionChange}/>
<input type="submit"/>
</form>
</div>
)
}
})
Is my ajax call which I send to my controller which has
def create
#cohort = Cohort.create(name: params[:name], description: params[:description])
render component: 'ShowCohort', props: { cohort: #cohort }
end
Which in my ajax success function, the data is the new React html code. How to I actually redirect the the page?
This is my React component to render
var ShowCohort = React.createClass ({
render: function() {
return (
<div className="container">
<h3>Hello {this.props.cohort.name}</h3>
<p>{this.props.cohort.description}</p>
</div>
)
}
})
Don't use ajax. Just use a regular form.
this should be like this
success: function(data, success, xhr) {
window.location.href = "redirect_url";
}
you can pass it as json as well like this in your controller
render json: {"redirect":true,"redirect_url": apps_path}, status:200
success: function(data, success, xhr) {
window.location.href = data.redirect_url;
}

How to stop explorer Json downloading strange bahaviour?

i can not bind Json data to table. Also internet explorer wants to download Json data. How to stop explorer download request and fill table. i have been reading more stackoverflow questions and googling articles. i can not understand why knockout.js cannot bind data. i have been learned binding arhitecture in knockout and json binding.
like That:
http://jsfiddle.net/madcapnmckay/3rRUQ/1/
http://jsfiddle.net/rniemeyer/5EWDG/
i would like to use binding theese methods. but i can not stopping iexplorer downloading behavior.
var result = function () {
$.ajax({
type: "get",
url: "/Contact/GetEmployees/",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
viewModel = ko.mapping.fromJS(data, self.Employees);
},
error: function (error) {
alert(error.status + "<--and--> " + error.statusText);
}
});
};
ko.utils.arrayMap(result, function (i) { Directory.list.push(new Employee(i.EmployeeCode, i.EmployeeName)); });
also :
#{
ViewBag.Title = "GetPerson";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>GetPerson</h2>
<script type="text/javascript">
function Person(FirstName, LastName, Friends) {
var self = this;
self.FirstName = ko.observable(FirstName);
self.LastName = ko.observable(LastName);
self.FullName = ko.computed(function () {
return self.FirstName() + ' ' + self.LastName();
})
self.Friends = ko.observableArray(Friends);
self.AddFriend = function () {
self.Friends.push(new Person('new', 'friend'));
};
self.DeleteFriend = function (friend) {
self.Friends.remove(friend);
};
}
var viewModel = new Person();
$(document).ready(function () {
$.ajax({
url: 'Person/GetPerson',
dataType: 'json',
type: 'GET',
success: function (jsonResult) {
viewModel = ko.mapping.fromJS(jsonResult, mapping);
console.log(viewModel);
ko.applyBindings(viewModel);
}
});
});
var mapping = {
create: function (options) {
var person = options.data,
friends = ko.utils.arrayMap(person.Friends, function (friend) {
return new Person(friend.FirstName, friend.LastName);
});
return new Person(person.FirstName, person.LastName, friends);
}
};
</script>
#using (Html.BeginForm())
{
<p>First name: <input data-bind="value: FirstName" /></p>
<p>Last name: <input data-bind="value: LastName" /></p>
<p>Full name: <span data-bind="text: FullName" /></p>
<p>#Friends: <span data-bind="text: Friends().length" /></p>
#*Allow maximum of 5 friends*#
<p><button data-bind="click: AddFriend, text:'add new friend', enable:Friends().length < 5" /></p>
#*define how friends should be rendered*#
<table data-bind="foreach: Friends">
<tr>
<td>First name: <input data-bind="value: FirstName" /></td>
<td>Last name: <input data-bind="value: LastName" /></td>
<td>Full name: <span data-bind="text: FullName" /></td>
<td><button data-bind="click: function(){ $parent.DeleteFriend($data) }, text:'delete'"/></td>
</tr>
</table>
}
Controller Method:
public class PersonController : Controller
{
//
// GET: /Person/
public ActionResult GetPerson()
{
Person person = new Person
{
FirstName = "My",
LastName = "Name",
Friends = new List<Person>
{
new Person{FirstName = "Friend", LastName="Number1"},
new Person{FirstName = "Friend", LastName="Number2"}
}
};
return Json(person, "text/html", JsonRequestBehavior.AllowGet);
//return Json(person, JsonRequestBehavior.AllowGet); Not working
}
}
How to solve binding and downloading problem?

Jsp ajax call using jquery

I have this code snippet where I am passing data to another jsp file.
Javascript
$(document).ready(function() {
$("#click").click(function() {
name = $("#name").val();
age = $("#age").val();
$.ajax({
type : "POST",
url : "pageTwo.jsp",
data : "name=" + name + "&age=" + age,
success : function(data) {
$("#response").html(data);
}
});
});
});
HTML
<body>
Name:<input type="text" id="name" name="name">
<br /><br />
Age :<input type="text" id="age" name="age">
<br /><br />
<button id="click">Click Me</button>
<div id="response"></div>
</body>
and in pageTwo.jsp, my code is
<%
String name = request.getParameter("name");
String age = request.getParameter("age");
out.println(name + age);
%>
but this is not working.Is any mistake in my Jquery ?.Can any one please help me?.
$("#click").click(function(e) {
// e.preventDefault();
...
return false;
});
and of course install firebug or use chrome default developer tools (f12). open console and run the code.
$(document).ready(function () {
$("#click").click(function () {
name = $("#name").val();
age = $("#age").val();
$.ajax({
type: "POST",
url: "pageTwo.jsp",
data: "{'name':'" + name + "','age':'" + age + "'}",
contentType: "application/json",
async: false,
success: function (data) {
$("#response").html(data.d);
}
});
});
});

load data from db knockoutjs + mv3

attached the file EXAMPLE: http://jsfiddle.net/brux88/9fzG4/1/
hi,
I'm starting to use knockoutjs in an asp.net mvc project.
i have a view :
<button data-bind='click: load'>Load</button>
<table>
<thead>
<tr>
<th>Cliente</th>
<th>Colli</th>
<th>Tara</th>
<th>Peso Tara</th>
<th> </th>
</tr>
</thead>
<tbody data-bind='foreach: righe'>
<tr>
<td>
<select data-bind="
value: selectedCli,
options: clienteList,
optionsText: function(item) { return item.Rscli + '-' + item.Codcli },
optionsCaption: '--Seleziona un Cliente--'"
style=" width: 150px">
</select>
</td>
<td >
<input data-bind='value: Ncolli' />
</td>
<td>
<select data-bind="value: selectedTara,
options: taraList,
optionsText: function(item) { return item.Destara +
'-' + item.Codtara},
optionsCaption: '--Seleziona un Cliente--'"
style=" width: 150px">
</select>
</td>
<td >
<input data-bind="value: Ptara" />
</td>
<td>
<a href='#' data-bind='click: $parent.rimuoviRiga'>Elimina</a>
</td>
</tr>
</tbody>
</table>
<button data-bind='click: aggiungiRiga'>Aggiungi</button>
<button data-bind='click: salva'>Salva</button>
<button data-bind='click: annulla'>Annulla</button>​
my result from data db:
[{"Codcli":4,"Rscli":"antonio","Codtart":"1002","Despar":"ciliegino","Ncolli":10,"Pcolli":100,"Codtara":"03","Destara":"","Ptara":82,"Pnetto":18,"Prezzo":1},{"Codcli":1,"Rscli":"bruno","Codtart":"1001","Despar":"pomodoro","Ncolli":10,"Pcolli":100,"Codtara":"03","Destara":"","Ptara":10,"Pnetto":90,"Prezzo":1}]
my viewmodel knockoutjs:
<script type="text/javascript">
var listCli= [{Codcli: 1,Rscli: "Bruno"},{Codcli: 2,Rscli: "Pippo"},{Codcli: 3,Rscli: "Giacomo"}];
var listTa= [{Codtara: 01,Destara: "Plastica",Pertara:4},{Codtara: 02,Destara: "Legno",Pertara:6},{Codtara: 03,Destara: "Ploto",Pertara:8}];
var mydataserver = [{"Codcli":3,"Rscli":"Giacomo","Ncolli":10,"Codtara":"03","Destara":"Legno","Ptara":82},{"Codcli":1,"Rscli":"Bruno","Ncolli":10,"Codtara":"02","Destara":"Plastica","Ptara":10}];
var RigaOrdine = function () {
var self = this;
self.selectedCli = ko.observable();
self.clienteList = ko.observableArray(listCli);
self.Ncolli = ko.observable();
self.selectedTara = ko.observable();
self.taraList = ko.observableArray(listTa);
self.Ptara = ko.observable();
self.Ncolli.subscribe(function () {
self.Ptara(self.Ncolli() ? self.selectedTara().Pertara * self.Ncolli() : 0);
});
self.selectedTara.subscribe(function () {
self.Ptara(self.Ncolli() ? self.selectedTara().Pertara * self.Ncolli() : self.selectedTara().Pertara);
});
};
var Ordine = function () {
var self = this;
self.righe = ko.observableArray([new RigaOrdine()]); // Put one line in by default
// Operations
self.aggiungiRiga = function () {
self.righe.push(new RigaOrdine());
};
self.rimuoviRiga = function (riga) {
self.righe.remove(riga);
};
self.salva = function() {
var righe = $.map(self.righe(), function (riga) {
return riga.selectedCli() ? {
Codcli: riga.selectedCli().Codcli,
Rscli: riga.selectedCli().Rscli,
Ncolli: riga.Ncolli(),
Codtara: riga.selectedTara().Codtara,
Ptara: riga.Ptara(),
} : undefined;
});
alert( ko.toJSON(righe));
//save to server
/* $.ajax({
url: "/echo/json/",
type: "POST",
data: ko.toJSON(righe),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data) {
}
});*/
self.righe([new RigaOrdine()]);
};
//load from server
self.load = function() {
$.ajax({ url: '/echo/json/',
accepts: "application/json",
cache: false,
statusCode: {
200: function (data) {
alert(ko.toJSON(mydataserver));
//i do not know apply to viewmodel
},
401: function (jqXHR, textStatus, errorThrown) {
alert('401: Unauthenticated');
// self.location = "../../Account/Login.html?returnURL=/Index.html";
}
}
});
};
self.annulla = function() {
self.righe([new RigaOrdine()]);
};
};
var viewmodel = new Ordine();
ko.applyBindings(viewmodel);
​
</script>
if I want to load data from a db, how do I? Whereas there are dropdownlist
Your question is a bit weak so I will give you a more general answer.
To answer your question regarding how to load data from a db, it looks like that you have started on the right track. Usually you use an AJAX request to do the async request of data. To do this, knockoutJS provides the following function:
$.getJSON("/some/url", function(data) {
// Now use this data to update your view models,
// and Knockout will update your UI automatically
})
Source: http://knockoutjs.com/documentation/json-data.html
In the callback provided you will have access to the data returned from the server. It depends on the logic of your application what you want to do here - for some applications it might make sence to update the state of the viewmodel to make corresponding updates in the view.
If your question is more specific, please elaborate. Otherwise, I hope I got you on the right track.
As i can see.. you may want some good pratice to load.
I'll share with you mine.
Well.. return a Json as an JsonResult.
// POST: /Client/LoadClient
[HttpPost]
public JsonResult LoadClient(int? id)
{
if (id == null) return null;
var client = _business.FindById((int) id);
return Json(
new
{
id = cliente.id,
name = cliente.name,
list = cliente.listOfSomething.Select(s => new {idItemFromList = s.idWhatever, nameItemFromList = s.nameWhatever})
});
}
JS
viewmodel.Client.prototype.LoadClient= function (id) {
var self = this;
if (id == 0) {
return null;
}
$.ajax({
url: actionURL("LoadClient", "Client"),
data: { id: parseInt(id) },
dataType: "json",
success: function (result) {
if (result != null)
self.Load(result);
}
});
Load method.
viewmodel.Client.prototype.Load = function (result) {
var self = this;
self.idClient(result.id);
self.nameCliente(result.name);
self.ListOfSomething(result.list);
};
and..
ko.applyBinding(yourModel);
as u can see I'm using prototype it's a good practice too.

Resources