I have a Kendo DataSource that takes its data from a remote server (Json) and it bind the data to a kendo template in the client-side.
On the client, right now I just display the Data. However, I want to add/remove data in the dataSource as well. How can I send the dataSource after modification back to server and store it in there ?
Here is a good example of what I am trying to do. While this example reads its data from a local variable, would you please let me know:
How can I store the dataSource on the server-side after user make modification on the client ?
http://jsfiddle.net/derickbailey/D4g8S/
For example the add method just update the datasource on the client side. However, I want to send it to the Server and store it some how there. As a results, if someone else open the same web page in another client, he/she can see the changes as well.
$("#add").click(function(e){
e.preventDefault();
var $todo = $("input[name='description']");
currentId += 1;
dataSource.add({
id: currentId,
done: false,
description: $todo.val()
});
$todo.val("");
$todo.focus();
});
I am using C# .Net MVC on the server side.
As I understand you are asking how you can made server changes based on changes on client side? If is that true you can do three things:
catch data which you modify (added, deleted, updated),
Serialize to JSON,
send to the controller's action.
Here is simple example how you can read data from your datasource:
var dataSource = new kendo.data.DataSource({
data: [
{ id: 1, name: "Jane Doe", age: 30 },
{ id: 2, name: "John Doe", age: 33 }
]
});
dataSource.fetch(function(){
// reading data from dataSource
var raw = dataSource.data();
// entire dataSource
alert("This is entire dataSource: " + JSON.stringify(raw));
// this is what will be removed
alert("This is removed: " + JSON.stringify(raw[0]));
dataSource.remove(raw[0]);
// this is what is rest
alert("This is rest: " + JSON.stringify(raw));
});
After you assign these data to some object you can serialize into JSON with: JSON.stringify(data) method.
Than you can post these data to controller's action and do some work. How to post JSON to MVC controller is common question, please read here.
For deleting and updating is similar. Basically you have to catch data which you want, serialize and post to action.
You can use the add method on the data source and specify there where to post the new data. There is an example in the KendoUI documentation. From there you can also configure the edit/remove methods.
To get JSON array from dataSource object use toJSON method
dataSource.data().toJSON()
then you can post it back to the server
Demo
Related
Objective:
When a table is updated with a new row (ParseFile + ParseUser + ParseUser), send one of the ParseUsers a push notification
When a new user is created, add a new row to a table (ParseFile + user)
Can either of these be easily achieved without jumping through some major hoops? I'm completely unfamiliar with Cloud Code, though I tried to read through some of the documentation. Cloud Code looks like it has the potential to perform this task, but I haven't seen any examples of doing something like I would like to do.
Does anyone have concrete examples of using Parse Cloud Code in conjunction with the .NET SDK and table updates?
Parse has a nice Documentation: Parse CloudCode
This is an example Code, which sends a push every time a user is created
//instead of Parse.User you can use any custom parse class too, but write them inside quotes
Parse.Cloud.afterSave(Parse.User, function(request) {
if(!request.object.existed()){//existed() returns false if the object was just created
var query = new Parse.Query(Parse.Installation);
query.equalTo("User", request.object);
Parse.Push.send({
where: query,
data: {
badge: "Increment",
alert: "Welcome " + request.object.get("username"),
sound: "beep.caf"
}
}, {
success: function(){
//succeed
},
error: function(err){
console.error("Got an error " + error.code + " : " + error.message);
}
});
}
});
There are also other hooks available:
beforeSave
afterSave
beforeDelete
afterDelete
Inside these hooks you can send push notifications, create new objects, manipulate objects, do nearly whatever you want.
In Parse CloudCode you can take advantage of the Parse JavaScript API.
In ASP.NET (web forms), I am retrieving a set of key/value pairs from an SQL database to be used in a DropDownList. This list is quite large (can be over 2000 entries) and used multiple times over many of the pages on the website and I've been looking into ways to cache this set of data on the local client to reduce bandwidth. The list doesn't change often so having a cached copy a week or more should be fine.
I wanted to know if it was at all possible and/or practical to have this list stored using HTML5 local storage and have a DropDownList fill from the client storage. If no data if found locally, then going on to query the database for the list.
If you have over 2000 entries in a select box it dosnt sound all that usable anyway.
Have a look at something like Select2. Particularly the "Loading Remote Data" example.
http://ivaynberg.github.io/select2/
I have been involved in writing a couple of apps where data is pushed back and forth regularly and we built an API object in Javascript to handle data being pulled from the server on request.
The API module requested data and took an action depending on its success status. You could build a simple API module to use if you feel that you may need to expand the type of data returning later, or just build a single AJAX call to pull the data for the drop down list.
An example of the API interface would be as such:
/**
* Parameter 1, string - Command Name for the server to interpret
* Parameter 2, object - Data that should be passed to the server (if necessary)
* Parameter 3, string - the HTTP method to use: 'GET', 'POST', 'PUT' etc.
* Parameter 4, function - the callback to fire once the response is received.
**/
api('CommandName', { key: 'value' }, 'METHOD', function(response) {
if(response.success) {
//Store data in localStorage here
}
});
As you stated above, you are using the data multiple times throughout the pages on your website. Therefore in the JavaScript you would write a check on load which determines if the data has been stored within the localStorage, and if not makes a call to the API to populate it. This would ensure that the client always has that data available. This can be done like so:
//On Load
if(!localStorage.dropdown) {
api('CommandName', { key: 'value' }, 'METHOD', function(response) {
if(response.success) {
localStorage.dropdown = response.data;
}
});
}
I'm aware that data can be passed in through the URL, like "example.com/thing?id=1234", or it can be passed in through a form and a "submit" button, but neither of these methods will work for me.
I need to get a fairly large xml string/file. I need to parse it and get the data from it before I can even display my page.
How can I get this on page load? Does the client have to send a http request? Or submit the xml as a string to a hidden form?
Edit with background info:
I am creating a widget that will appear in my customer's application, embedded using C# WebBrowser control, but will be hosted on my server. The web app needs to pass some data (including a token for client validation) to my widget via xml, and this needs to be loaded in first thing when my widget starts up.
ASP.NET MVC 4 works great with jQuery and aJax posts. I have accomplished this goal many times by taking advantage of this.
jQuery:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "/{controller}/{action}/",
data: { clientToken: '{token}', foo: 'bar',
success: function (data, text) {
//APPEND YOUR PAGE WITH YOUR PARSED XML DATA
//NOTE: 'data' WILL CONTAIN YOUR RETURNED RESULT
}
});
});
MVC Controller:
[HttpPost]
public JsonResult jqGetXML(string clientToken, string foo)
{
JsonResult jqResult = new JsonResult();
//GET YOUR XML DATA AND DO YOUR WORK
jqResult.Data = //WHATEVER YOU WANT TO RETURN;
return jqResult;
}
Note: This example returns Json data (easier to work with IMO), not XML. It also assumes that the XML data is not coming from the client but is stored server-side.
EDIT: Here is a link to jQuery's Ajax documentation,
http://api.jquery.com/jQuery.ajax/
Assuming you're using ASP.NET, since you say it's generated by another page, just stick the XML in the Session state.
Another approach, not sure if it helps in your situation.
If you share the second level domain name on your two sites (i.e. .....sitename.com ) then another potential way to share data is you could have them assert a cookie at this 2nd level with the token and xml data in it. You'll then be provided with this cookie.
I've only done this to share authentication details, you need to share machine keys at a minimum to support this (assuming .Net here...).
You won't be able to automatically upload a file from the client to the server - at least not via a browser using html/js/httprequests. The browser simply will not allow this.
Imagine the security implications if browsers allowed you to silently upload a file from the clients local machine without their knowledge.
Sample solution:
Background process imports xml file and parses it. The background process knows it is for customer YYY and updates their information so it know the xml file has been processed.
A visitor goes to the customer's web application where the widget is embedded. In the markup of the widget the customer token has been added. This could be in JavaScript, Flash, iFrame, etc.
When the widget loads, it makes a request to you app which then checks to see if the file was parsed for the provided customer (YYY) if it has, then show the page/widget.
If the XML is being served via HTTP you can use Liqn to parse the data.
Ex.
public partial class Sample : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string url = "http://news.yahoo.com/rss/";
var el = XElement.Load(url).Elements("channel");
StringBuilder output = new StringBuilder();
foreach (var c in el.Elements())
{
switch (c.Name.LocalName.ToLower())
{
case "title":
output.Append(c.Value);
output.Append("<br />");
break;
}
}
this.Label1.Text = output.ToString();
}
}
It is not exactly clear what the application is and what kind of options you have, and what kind of control over web server you have.
If you are the owner of the web server/application your options are way wider. You can first send a file to web-server with HTTP POST or PUT, including a random token, and then use the same token for GET with token in the query string
or use other options, applicable to third party-owned websites
if you are trying to consume some auth api, learn more about it. since you are hosting web browser control, you have plenty of options to script it. including loading whatever form, setting textarea or hidden field text with your xml and then simulating a submit button click. you can then respond to any redirects and html responses.
you can also inject javascript inside the page that would send it to server with ajax request.
the choice heavily depends on the interaction model.
if you need better advice, it would be most helpful if you provided sample/simplified url/url pattern, form content, and sequence of events that is expected from you from code/api/sdk perspective. they are usually quite friendly.
There are limited number of ways to pass data between pages. Personally for this I would keep in session during the generating page and clear it when it is retrieved in the required page.
If it is generated server side then there is no reason to retrieve it from client side.
http://msdn.microsoft.com/en-us/library/6c3yckfw(v=vs.100).aspx
Create a webservice that your C# app can POST the XML to and get back HTML in response. Load this HTML string into the WebBrowser control rather than pointing the control to a URL.
I have a jQuery Countdown Timer that I am using, and I need to be able to access my Database and perform some calculations and then return the result:
$('#expireMessage').countdown({until: shortly,
expiryText: '<div class="over">It\'s all over</div>'});
$('#expireMessageStart').click(function() {
shortly = new Date();
shortly.setSeconds(shortly.getSeconds() + 5.5);
$('#expireMessage').countdown('change', {until: shortly});
});
Now, the above code just displays a countdown timer, and counts down. And when it hits
00:00:00
it displays a message "It's all over".
But what I need it to do is display a different message depending on the result of the DB calculations.
The DB work I can do, but I'm not sure how to go about retrieving that info from the database when using jQuery. I'd really appreciate your help.
Thank you
You need to set up something on the server side to talk to the database for you, then return the result in JSON format. What that something is depends on what your server-side code is written in. Are you using PHP? Java? ASP.NET?
I work primarily in ASP.NET, so one way I might tackle this is adding a WebMethod to my page that executes a database query, builds the message, serializes it to JSON, and returns it to the client.
In your JavaScript, you'll want to execute either an XMLHttpRequest (if you're using regular JavaScript) or a jQuery AJAX request.
Here's a very simple example of what a jQuery AJAX call might look like:
$.ajax({
url: 'http://mysite.com/getmymessage',
success: function( data ) {
// Here's where you'd update your countdown display, but I'm just writing to the console
console.log( 'The server says: ' + data.myDbResult );
}
});
I need to refresh sections of my page to update when there is new data! what do i do? use jquery?
examples:
Yes, jQuery's great for this. Look into these methods:
http://api.jquery.com/category/ajax/
jQuery is usually not needed for basic AJAX. A simple example could be as follows:
liveSection = document.getElementById('latest-news');
request = new XMLHttpRequest;
request.open('GET', '/news-ajax', true);
request.send(null);
request.addEventListener('readystatechange', function() {
if (request.readyState == 4 && request.status == 200)
liveSection.innerHTML = request.responseText;
}, false);
If you're using Asp.NET, why not use an UpdatePanel? It's simple and reliable.
Edit
I just re-read your question and it looks (based on how you worded it) that you want to update a user's web page when the data changes on the server. I just want to make sure you understand that in a web app, the server can't trigger the browser to do anything. The server can only respond to browser requests, so you'll need to have the browser poll the server periodically.
I've created a simple example (using jQuery) to help you understand the breakdown of the things that will need to happen, which are:
1 - Periodically polling the server (via ajax) using Javascript's setTimeout to check that what is loaded into the browser is the latest content. We can achieve this by fetching the latest item ID or whatever and comparing it to a variable, which was initialised when the page first loaded.
2 - If the item ID does not match (a bit of an oversimplification) then we can assume that there has been an update, so we replace the content of some element with some content from some page.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
function getLatestStuff() {
// fetch the output from a context which gives us the latest id
$.get("isthereanupdate.aspx", function(response) {
// we have the response, now compare to the stored value
if(resp != lastItemId) {
// it's different, so update the variable and grab the latest content
lastItemId = response;
$("#latestStuffDiv").load("updates.aspx");
}
});
}
$(document).ready(function() {
// the value which initializes this comes from the server
var lastItemId = 7;
setTimeout(getLatestStuff, 10000);
});
</script>
If you want to update when there is new data, you should look into comet or pubsubhubbub. jQuery can help you display the data in a pretty way, but you'll need to write stuff on the serverside to send the data.