Kendo UI Mobile Listview always display [object Object] - wcf

I'm using Kendo UI Listview control to display Categories data from WCF Service. the problem is always the list view instead of displaying the "Name" of the Category, it display [object Object].
the Json Data returned from the service is like
d
Items
ID=1
Name=Sports
IsActive=true
the HTML code:
<body>
<div data-role="view" data-init="mobileListViewPullWithEndless">
<ul id="grouped-listview"></ul>
</div>
<script>
var categoriesTransport = new kendo.data.RemoteTransport({
read: {
url: "http://localhost:11124/Services/PublishingMobileService.svc/GetAllCategories", //specify the URL which data should return the records. This is the Read method of the Products.svc service.
contentType: "application/json; charset=utf-8", // tells the web service to serialize JSON
dataType: 'json',
type: "POST" //use HTTP POST request as the default GET is not allowed for svc
},
parameterMap: function (data, operation) {
if (operation != "read") {
// web service method parameters need to be send as JSON. The Create, Update and Destroy methods have a "products" parameter.
return JSON.stringify(data);
} else {
return JSON.stringify(data);
}
}
});
function mobileListViewPullWithEndless(e) {
$("#grouped-listview").kendoMobileListView({
height: 400,
dataSource:kendo.data.DataSource.create( {
schema: {
data: "d.Items", // svc services return JSON in the following format { "d": <result> }. Specify how to get the result.
},
transport: categoriesTransport,
template: $("#endless-scrolling-template").text(),
}),
});
}
</script>
<script type="text/x-kendo-tmpl" id="endless-scrolling-template">
<div>
<h3>#:ID#</h3>
</div>
</script>
<script>
var app = new kendo.mobile.Application(document.body);
</script>
Could you please help on that.?

I understand this question is a bit old, but for future reference:
I had this exact issue recently when I bound to an observable without a template. Adding the template as you have gave me the same issue, whereas adding like this works:
<ul id="accomodations-list"
data-role="listview"
data-style="inset"
data-bind="source:accommodations"
data-template="template"></ul>

Related

Nuxt3 useFetch sends request only once

<script setup lang="ts">
const loadPost = () => {
console.log('load')
const { data, pending, error, refresh } = useFetch(
'https://jsonplaceholder.typicode.com/posts',
{
method: 'POST',
body: {
title: 'foo',
body: 'bar',
userId: 1,
},
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
console.log(data)
}
</script>
<template>
<div class="max-w-xs space-y-4 mx-auto mt-4">
<button #click.prevent="loadPost">Load post</button>
</div>
</template>
After clicking on the load button, I see every time the request is processed through the console log, but I do not see a new request in the network chrome devtools, I need to receive a response from the server every time, how can I do this?
Note: If I use a regular fetch(), then the request is sent every time, as it should be
my nuxt version - 3.0.0-rc.1
Thanks! Solved by adding param initialCache: false
useFetch('https://reqres.in/api/users?page=2?delay=1', { initialCache: false })
If you want to re-fetch the data, use the refresh() method returned from useFetch():
<script setup lang="ts">
const { data, pending, error, refresh } = await useFetch('https://reqres.in/api/users?page=2?delay=1')
const loadPost = () => {
refresh()
}
</script>
demo
Watch out! you need a key. In you don't provide one, will generate it from the URL. This might not get you the result you expect. Generate a different key if the data will change.
Here is in the docs
Options (from useAsyncData):
key: a unique key to ensure that data fetching can be properly de-duplicated across requests, if not provided, it will be generated based on the url and fetch options.

Vue JS: how to async load and render components when they are visible in the viewport

I am relatively new to Vue JS, and I am working on a website that publishes articles that contain different types of content (videos, images) and polls (multiple poll forms on the same page). The site is running on CraftCMS & MySQL, so the content of the templates is parsed server sided.
I created a poll component so I could reuse it on the same page. Works fine, but then all data in the template is loaded on initial page load, which I would like to prevent due to large queries.
The solution (which I was also using before I started rebuilding this site with Vue JS), is to load these parts async when they're in the viewport. With a combination of a viewport detection library and jQuery I simply loaded the Craft template (/includes/poll). But now it's built with Vue, I am a little bit confused on how to manage this.
After hours of searching, I got the async part working, using a async component, but this will still load and render all components after the page is loaded, even when they're not visible for the user.
So far, this is what I got:
CraftCMS template (/includes/poll)
Note: tags will be parsed server sided by Craft, not Vue
<poll inline-template>
<div id="poll-component-{{ id }}" >
{% if userHasVoted %}
show results of poll
{% else }
show poll form that will fire vote()
{% endif %}
</div>
</poll>
Async component
Vue.component('poll', function(e) {
return {
component: new Promise(function(resolve, reject) {
// Request
axios.get('/includes/poll', {
params: {
id: 123, // NEED TO GET THIS FROM HTML ATTRIBUTE
}
})
.then((response) => {
resolve({
template: response.data,
created() {
},
mounted () {
},
props: {
id: String,
title: String,
},
data () {
return {
hasVoted: false,
isVoting: false
}
},
methods: {
vote: function() {
// API call to server, send vote, on success reload the poll template again (includes/poll)
}
}
})
}, (error) => {
console.log(error);
});
}),
loading: Vue.component('loader', {
template: '<p>loading...</p>'
}),
error: Vue.component('load-error', {
template: '<p>error loading component</p>'
}),
delay: 200,
timeout: 10000
}
});
And in my Craft templates I add the html element:
<poll id="123"></poll>
I got 2 problems:
I can't pass the id to the axios/http/get call, which is required show the right poll data
The component is always loaded even when it's not in the viewport
Hope anybody can advise me on this one. Thanks!

How to bind the same template multiple times in vue.js?

Submitting a page form results in an ajax call to a backend service which returns an json object. The object is than bound to a vue.js template (a div with a particular id). Everythiong works as expected on the first submit. However, the view is not updated on any following form submits (it still shows the data from the first submit).
<div id="Response"></div>
$('#Form').submit(function (e) {
e.preventDefault();
var $form = $(e.target);
$.ajax({
url: 'https://somewhere,
type: 'POST',
data: $form.serialize(),
dataType: 'json',
success: function(response) {
if (response) {
var app = new Vue({
el: '#Response',
data: response
});
}
}
});
});
How to do this properly so each time the form is submitted, the view is updated appropriately based on the last response?
Now you are creating a new vue instance with each response. You need to mount the vue instance first, then use the response to update the data in it.

MVC 4 View Knockout Bindings not updating on ajax call

I have gone through as many questions on here as I could find and tried all the different suggestions and cannot get this to work. I have a view that is bound with Knockout using the mapping plugin and it works okay but only when I do the "wrong thing". Everything that I have read says that you should only make one call to ko.applyBindings() per view and then everything should update using ko.mapping.fromJS(). I cannot seem to get this to work, the only way I have been able to get my view to refresh is to call ko.applyBindings() again in the success call back from my .ajax() call. Here is the offending code.
<script type="text/javascript">
var viewModel;
$(document).ready(function() {
$("#panelbar").kendoPanelBar({
expandMode: "multiple"
});
$.ajax({
type: 'GET',
url: '/Home/IsUserMarketingManager',
success: function (data) {
if (data == true) {
$('#submitNewCase').hide();
$('#approveCase').show();
$('#disapproveCase').show();
}
}
});
// Generate client View Model from Server View Model
viewModel = new ViewModel();
ko.mapping.fromJS(#Html.Raw(Json.Encode(Model)),{}, viewModel);
ko.applyBindings(viewModel);
});
function ViewModel () {
var self = this;
self.addLocation = function() {
self.AdditionalLocations.push({ GaNumber: "" });
};
}
</script>
And later this to update the form with retrieved data:
<script type="text/javascript">
$('#btnImport').click(function () {
$.blockUI({ message: '<h2>Importing Client Information...</h2> <img src="/Images/ajax-loader.gif"><br />' });
$.ajax({
type: 'post',
url: '/Home/ImportClientCrmInfoJson',
dataType: "json",
data: ko.mapping.toJS(viewModel),
success: function (data) {
$.unblockUI();
if (!data.AccountNull) {
ko.mapping.fromJS(data, {}, viewModel);
} else {
alert("Could not find account for this GA Number, please try again.");
}
}
});
});
</script>
When submitting the form to my controller, all the data is there and mapped correctly to my server side View Model, but the form in the view isn't updated with the data that comes back from the $.ajax call. I've gotten the form to update if I do the following, but I know it's not the right way and has caused me other issues as well.
<script type="text/javascript">
$('#btnImport').click(function () {
$.blockUI({ message: '<h2>Importing Client Information...</h2> <img src="/Images/ajax-loader.gif"><br />' });
$.ajax({
type: 'post',
url: '/Home/ImportClientCrmInfoJson',
dataType: "json",
data: ko.mapping.toJS(viewModel),
success: function (data) {
$.unblockUI();
if (!data.AccountNull) {
viewModel = ko.mapping.fromJS(data);
ko.applyBindings(viewModel); // This works but isn't the right way...
} else {
alert("Could not find account for this GA Number, please try again.");
}
}
});
});
</script>
Any help would be much appreciated.
Have you examined that the following line of code appears to create a 'NEW' viewmodel?
viewModel = ko.mapping.fromJS(data);
When you do this the new viewModel the old bindings are destroyed. This is why you have to call ApplyBindings again. Anyway, I think the above line of code is the root of the problem.
Is there a way for you to create an observable property on the viewModel and allow the viewModel to reflect the data in this object? That may be a more practical approach to the update process.
In the success callback of the ajax call, use this method ko.applyBindings(viewModel) but pass as a second parameter the DOM portion you want to update as follows
ko.applyBindings(viewModel, $("#mydiv")[0])
Don't use a jquery object but a REAL DOM object.

How to get the load event before ajax call to PHP returns

I would like my webpage to render faster. Based on this article, I understand that the page renders when the 'load' event is fired.
When I look at the Network Tab of my Chrome browser, I see that the 'load' event is fired after an ajax call to a PHP script returns.
Webpage is live at http://www.99like.com/index.php
=> Is there any way to get the page to render before the PHP script is called?
Following is the extract of the code which I think is relevant for the question:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="highcharts.js"></script>
<script type="text/javascript">
var ajax_load = "<img class='loading' src='images/load.gif' alt='loading...' />";
var inputForm = "<div class='shadow'><form type='submit' onsubmit='displayChart(); return false'><input id='searchBox' type='text' size='30' value='search keyword' /></form></div>";
var chart = "<div id='chart' class='shadow'></div>";
var chartPage = inputForm + chart;
$(function ()
{
exampleChart();
});
function exampleChart() {
$('#searchBox').val("hotel"); // nice example
displayChart ();
}
function displayChart () {
var keyword = $('#searchBox').val();
var chart = new Highcharts.Chart({ ... });
chart.showLoading();
var phpFunctionURL = "getChartData.php";
var DataSeries;
$.ajax( {
url: phpFunctionURL,
dataType: 'json',
async: false,
data: { ... },
success: function(json) { DataSeries = json; }
} );
}
</script>
A few remarks:
Make sure all your JavaScript are at the bottom of the page, including JQuery and Google Analytics code
Your web-page is missing the end tag
If needed, you could wait for the onLoad event to launch your AJAX request instead of the DomReady event, this will speed up the page rendering.
Looks like your AJAX request is synchronous. Making it asynchronous will solve the problem.
$.ajax( {
url: phpFunctionURL,
dataType: 'json',
async: true, // Changed from false to true
data: { ... },
success: function(json) { DataSeries = json; }
} );