My application has many items in the viewModel and I would like to see those values displayed in an alert box so I can see what is actually stored in there. When trying to pass this view model back to my controller I am not seeing any values, instead I am getting an error that 'viewModel' is not defined.
Here is an example of my view model script
$(document).ready(function () {
function ViewModel() {
var self = this;
self.SectionId = ko.observable("");
self.SectionName = ko.observable("");
var SectionNames = {
Id: self.SectionId,
Name: self.SectionName
};
self.selectedSectionName = ko.observable();
self.SectionNames = ko.observableArray();
// Initialize the view-model for Work Sections
$.ajax({
url: '#Url.Action("GetSections", "Home")',
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: {},
success: function (data) {
self.SectionNames(data);
}
});
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
});
Similar to creating a global variable or class level variable I would like to have this viewModel contain all of the current values for all of my observable items.
Except for the missing closing tag (as mentioned by #CSharper) your code will not throw the error you speak of. The answer to your question lies either in that missing closing tag, or in another piece of code not shown.
Here's how you can check, by mixing your code (+ closing tag) with a $.ajax stub:
$.ajax = function() {}; // Noop stub.
$(document).ready(function () {
function ViewModel() {
var self = this;
self.SectionId = ko.observable("");
self.SectionName = ko.observable("");
var SectionNames = {
Id: self.SectionId,
Name: self.SectionName
};
self.selectedSectionName = ko.observable();
self.SectionNames = ko.observableArray();
// Initialize the view-model for Work Sections
$.ajax({
url: '#Url.Action("GetSections", "Home")',
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: {},
success: function (data) {
self.SectionNames(data);
}
});
}
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
$root = <code data-bind="text: ko.toJSON($root)"></code><br />
No errors on console.
Related
I have the following request to the jsreport engine:
$.ajax({
method: "POST",
contentType: "application/json",
dataType: "jsonp",
url: "http://localhost:5488/api/report",
data: {
template: {
shortid: "ry6HoQRee"
},
data: {
"D": "5"
}
},
success: function (s) {
window.open("data:application/pdf,base64," + escape(s.responseText));
},
error: function (s) {
console.log(s);
}
});
However I can't find a way to read it inside the report template:
<span>{{data.D}}</span>
How do I refer to the data object that is inside the POST body
jquery doesn't support binary responses like pdf. You should rather use XMLHttpRequest:
var xhr = new XMLHttpRequest()
xhr.open('POST', 'http://localhost:5488/api/report', true)
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8')
xhr.responseType = 'arraybuffer'
xhr.onload = function(e) {
if (this.status == 200) {
window.open("data:application/pdf;base64," + window.btoa(String.fromCharCode.apply(null, new Uint8Array(xhr.response))));
}
}
xhr.send(JSON.stringify({
template: {
shortid: 'Syeopu_xe'
},
data: {
'D': '5'
}
}))
Example of reaching data using handlebars templating engine
<span>{{D}}</span>
Additionally...
You may also take a look at jsreport official browser client library. It wraps the XmlHttpRequest calls into more elegant calls:
jsreport.serverUrl = 'http://localhost:3000';
var request = {
template: {
content: 'foo', engine: 'none', recipe: 'phantom-pdf'
}
};
//display report in the new tab
jsreport.render('_blank', request);
or in async fashion
jsreport.renderAsync(request).then(function(res) {
//open in new window
window.open(res.toDataURI())
//open download dialog
res.download('test.pdf')
});
I want to bind my multiselect with ajax but after ajax call items does not show.I try rebuild or refresh multiselect but it still does not show
<script type="text/javascript">
$(document).ready(function () {
var categCheck = $('#multiselect').multiselect({
includeSelectAllOption: true,
enableFiltering: true
});
$.ajax({
type: 'GET',
url: "#Url.Content("~/Home/Listpositions/")",
success: function (data) {
$.each(data.data, function (index, item) {
alert(item.PositionName);
var opt = $('<option />', {
value: item.PID,
text: item.PositionName
});
opt.appendTo(categCheck);
});
}
});
$('#multiselect').multiselect('rebuild');
categCheck.multiselect('rebuild');
categCheck.multiselect('refresh');
$("select.multiselect").multiselect("refresh");
});
</script>
Here is my multiSelect page link:http://pratikisara.com/Home/Quick
How can I make ajax call from multiselect JS file(enter link description here) and in which code block should I do ajax call?
You need to to the rebuild and/or refresh in the AJAX success function. In your code, the AJAX call is made, then the multiselect is rebuild. But the rebuilt may happen before the AJAX call succeeds. Try this:
<script type="text/javascript">
$(document).ready(function () {
var categCheck = $('#multiselect').multiselect({
includeSelectAllOption: true,
enableFiltering: true
});
$.ajax({
type: 'GET',
url: "#Url.Content("~/Home/Listpositions/")",
success: function (data) {
$.each(data.data, function (index, item) {
alert(item.PositionName);
var opt = $('<option />', {
value: item.PID,
text: item.PositionName
});
opt.appendTo(categCheck);
// Rebuild after adding the options!
$('#multiselect').multiselect('rebuild');
});
}
});
});
</script>
by using reload its working fine for me. multiselect("reload") function refresh checkbox list in ajax call.
var obj_ddl_ExistingIdea = $("#ddl_ExistingIdea");
if (response.length > 0) {
for (var i = 0; i < response.length; i++) {
var str_newOption = '';
str_newOption = "<option value='" + response[i].IdeabookId + "'>" + response[i].Name + "</option>";
obj_ddl_ExistingIdea.append(str_newOption);
}
obj_ddl_ExistingIdea.multiselect("reload"); //using reload its working for me
$('#sltHeadCountdetailsCategorySiteCode').empty();
$("#sltHeadCountdetailsCategorySiteCode").multiselect('destroy');
This Is 100% fine code....
$(document).ready(function() {
var chkreport = $('#reporting_unit'); // Object creation for your dropdown
var ajaxpath = 'ajax/fend.php';
var ajaxUrl = baseUrl + ajaxpath;
$('#hospital_category').on('change', function() {
var hospital_id = this.value;
//alert(hospital_id);
$.ajax({
method: 'POST',
url: ajaxUrl,
data: {
perform_action: 'reporting_list',
hospital_id: hospital_id
},
dataType: 'html',
success: function(result) {
chkreport.append(result); // append option in the object created before ajax calling
// Now call multiselect function with their parameter
chkreport.multiselect({
columns: 1,
placeholder: 'Select Reporting Unit',
search: true,
selectAll: true
});
chkreport.multiselect('rebuild'); // it will reload dropdown need to create multiselect with checkbox option.
}
});
});
});
I was hoping to get a value (an object store) calling my dojo module, but I keep getting undefined :
module:
define(['dojo/store/Memory', 'dojo/_base/xhr', "dojo/data/ObjectStore"],
function (Memory, xhr, ObjectStore) {
var oReachStore;
return {
Reaches: function (url) {
xhr.get({//get data from database
url: url,
//url: url,
handleAs: "json",
load: function (result) {
var ReachData = result.GetReachesResult;
var ReachStore = new Memory({ data: ReachData, idProperty: "label" });
oReachStore = new ObjectStore({ objectStore: ReachStore });
},
error: function (err) { }
});
},
GetReaches: function () {
return oReachStore;
}
}
});
calls to module:
Data.Reaches(dataServiceUrl);//set the reach object store
ReachData = Data.GetReaches();//get the reach object store, but is always undefined
Like you probably noticed by now (by reading your answer), is that you're using an asynchronous lookup (the XMLHttpRequest is asynchronous in this case), but you're relying on that store, before it might be set.
A possible solution is the use of promises/deferreds. I don't know which Dojo version you're using, but in Dojo < 1.8 you could use the dojo/_base/Deferred module and since 1.8 you can use the dojo/Deferred module. Syntax is slightly different, but the concept is the same.
First you change the oReachStore to:
var oReachStore = new Deferred();
Then, inside your Reaches function you don't replace the oReachStore, but you use the Deferred::resolve() function, for example:
return {
Reaches: function (url) {
xhr.get({//get data from database
url: url,
//url: url,
handleAs: "json",
load: function (result) {
var ReachData = result.GetReachesResult;
var ReachStore = new Memory({ data: ReachData, idProperty: "label" });
oReachStore.resolve(ew ObjectStore({ objectStore: ReachStore })); // Notice the difference
},
error: function (err) { }
});
},
GetReaches: function () {
return oReachStore;
}
}
Then in your code you could use:
Data.Reaches(dataServiceUrl);//set the reach object store
Data.GetReaches().then(function(ReachData) {
console.log(ReachData); // No longer undefined
});
So now the ReachData won't return undefined, because you're waiting until it is resolved.
Deferreds are actually a common pattern in the JavaScript world and is in fact a more solid API compared to defining your own callbacks. For example, if you would get an error in your XHR request, you could use:
error: function(err) {
oReachStore.reject(err);
}
A simple example (I mocked the asynchronous request by using setTimeout()) can be found on JSFiddle: http://jsfiddle.net/86x9n/
I needed to use a callback function for the function GetReach. The following modified code worked:
Module:
define(['dojo/store/Memory', 'dojo/_base/xhr', "dojo/data/ObjectStore"],
function (Memory, xhr, ObjectStore) {
return {
GetReach: function (url, callback) {
xhr.get({//get data from database
url: url,
//url: url,
handleAs: "json",
load: function (result) {
var ReachData = result.GetReachesResult;
var ReachStore = new Memory({ data: ReachData, idProperty: "label" });
var oReachStore = new ObjectStore({ objectStore: ReachStore });
callback(oReachStore);
},
error: function (err) { }
});
}
}
});
call from main page:
// ....
Data.GetReach(dataServiceUrl, SetReach);
function SetReach(data) {
//set data for the dropdown
ddReach.setStore(data);
}
I'm studying Ember.js myself and I'm stuck with a problem I'm creating a sample app and I need to send the client side values to Server Side but I dont know how to do that I know the traditional way like the below code
function create() {
var data = {
'EmailID': $('#emailid').val(),
'password': $('#password').val()
}
$.ajax({
url: '/EmberNew/Home/Create',
type: 'POST',
data:data,
success: function (response) {
alert("hi");
}
});
return false;
}
but In Ember i dont Know How to do that my current code is given below
//Application
App = Em.Application.create();
//Model
App.Users = Em.Object.extend({
name: null,
password:null
});
//View
App.UserTextField = Em.TextField.extend({
insertNew: function () {
App.alertController.alertDetails();
}
});
App.PassTextField = Em.TextField.extend({
insertNew: function () {
App.alertController.alertDetails();
}
});
//controller
App.AlertController = Em.ObjectController.extend({
content: [],
username: '',
password: '',
alertDetails: function () {
var me = this;
var username = me.get("username");
var password = me.get("password");
alert('The User Name Is' + 'username' + 'And Password Is' + 'password');
}
});
App.alertController = App.AlertController.create();
I got the textbox values from alertDetails function and how can I pass them to server side
App.Record = Ember.Object.extend({
name: '',
other: ''
}).reopenClass({
records: [],
find: function() {
var self = this;
$.ajax({
url: "/api/records/",
type: "GET",
cache: false,
dataType: "json",
beforeSend: function() {
//if you want to call this often and need to clear + reload it
return self.records.clear();
},
success: function(results) {
var result;
for (_i = 0, _len = results.length; _i < _len; _i++) {
result = results[_i];
self.records.push(self.records.addObject(App.Record.create(result)));
}
},
error: function() {
return alert("error: failed to load the records");
}
});
return this.records;
}
});
Now that you have your model setup, you can call it from your route model hook
App.RecordsRoute = Ember.Route.extend({
model: function() {
return App.Record.find();
}
});
The find method returns an empty array right away, your template is then bound to it. When the ajax call returns w/ success and you update that array the handlebars template will update it for you w/out any DOM or jQuery glue code
I have an ajax enabled WCF service method :
[OperationContract]
public string Test(string name)
{ return "testing testing." + name; }
and I am calling it with following code:
$(document).ready(function () {
var varData = $("#NewSkill").val();
$("#Button1").click(function () {
$.ajax({
type: "POST",
url: "TimeService.svc/Test",
data: '{"name" : "John"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
}
});
});
});
I want to call this method continuously after every 5 seconds using above code . How can I do this ?
Move the $.ajax(); part to a Javascript function say AjaxCall(). Create a javascript variable
var isActivated = false;
$(document).ready(function () {
while(isActivated){
setTimeout("AjaxCall()",3000);
}
}
);
$("#Button1").click(isActivated = true)
Hope this helsps...