data binding in Kendo mobile - json

I am doing a kendo mobile application and I'm trying to bind data from database for listing using json call. I tried with the following code,but its not working Pls help me with this...thanks in advance...
my code is here:
$(document).ready(function () {
var dataSource = new kendo.data.DataSource({
transport: {
read: {
type: "POST",
url: "WebService/listing.php",
contentType: 'application/json; charset=utf-8',
datatype: "json"
}
}
});
dataSource.bind("change", function () {
$("#content").html(kendo.render(template, dataSource.view()));
});
dataSource.read();
console.log(dataSource.view());
});

You could try to use the changefunction of the dataSource directly:
var dataSource = new kendo.data.DataSource({
transport: {
read: {
type: "POST",
url: "WebService/listing.php",
contentType: 'application/json; charset=utf-8',
datatype: "json"
}
},
change: function() {
$("#content").html(kendo.render(template, this.view()));
}
});
Just some things to consider:
I'm assuming your JSON is correct
You're sure you use POST to get the data
your template is as well defined correctly
You're calling dataSource.read() AFTER the data is loaded (to make sure you're doing this, call read() within $(document).ready(function(){dataSource.read();}); and define the dataSource itself first
I guess the last point is the most crucial ;)
That's all I am doing, so if it doesn't work that way there might be some mistake in the data format itself or in the template definition. Anything like console errors?Cheers

Related

AJAX/JSON MVC method not being called

The MVC controller method is not being called with the following code and the issue isn't clear. $("#screeners").val() returns a list of strings:
<script>
$(document).ready(function () {
$("#submitScreeners").click(function () {
var selected = $("#screeners").val();
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Applicant/PassScreeners',
data: "selected=" + JSON.stringify(selected),
success: function () {
$('#result').html('"PassScreeners()" successfully called.');
},
failure: function (response) {
$('#result').html(response);
}
});
});
});
</script>
Method in controller:
public void PassScreeners(List<string> selected)
{
Session["SelectedApplicants"] = selected.Select(e => Int32.Parse(e.ToString())).ToList();
}
If I understand you correctly, the "selected" parameter is being passed in as a null value. I believe this is because you are using an incorrect data format. You tell the server to expect JSON formatted data, but then pass it something more akin to a form value with '='.
Try removing the "selected=" bit from your data line and just pass the stringified list.
If that doesn't work, check the trace and post it. If the string you are posting is just comma separated or something it needs to be an array in order for the POST to work correctly.
Apologies if I've misunderstood.

JSON passed to controller has no value

I am unable to get my JSON to my controller, and I can't figure out why the value I get in javascript isn't being passed to the controller. Here is my ajax post in my javascript:
this.save = function () {
var data = ko.toJSON(this.Routines);
$.ajax({
type: 'POST',
url: "CreateJson",
data: data,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
if (!result.success)
alert("test")
else { }
}
})
}
now data contains
[{"routine_name":"new routine","duration":"20","rest":"10","rounds":1}]
which is what I want, but the controller shows nothing. Here is my controller
[HttpPost]
public JsonResult CreateJson(t_routine routine, string data)
{
var message = "success";
return Json(message);
}
As I understand it, MVC 3+ automatically receives JSON without any need for parameters like my string data, I just threw it in there to try and figure out if I'm getting anything at all. data is null and routine shows 0's and null for values. What am I missing?
If t_routine represents the server side type for
[{"routine_name":"new routine","duration":"20","rest":"10","rounds":1}]
Then it might be enough to call JSON.stringify on the ko.toJSON result like this
this.save = function () {
var data = JSON.stringify(ko.toJSON(this.Routines));
$.ajax({
type: 'POST',
url: "CreateJson",
data: data,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
if (!result.success)
alert("test")
else { }
}
})
}
the data parameter on your controller action is not needed then and you most likely need to change the t_routine parameter to t_routine[]

Using HTTP GET with JQuery

I'm trying to use a GET HTTP cal, I got the request to work with the Advanced REST client (Chrome plugin) but cannot get it to work in JQuery.
Following the advice from this thread, I've set up the following:
$(document).ready(function() {
$('.ap1').click(function(){
$.ajax({
url: 'https://api2.panopta.com/v2/monitoring_node/41',
type: 'GET',
dataType: 'json',
success: function() { alert('hello!'); },
error: function() { alert('boo!'); },
beforeSend: setHeader
});
});
function setHeader(xhr) {
//extra stuff from REST CLIENT
xhr.setRequestHeader('Authorization', 'ApiKey nGhhAjGshbOu4dhLYvGY');
} });
This is the output I'm trying to get (successfully with REST client)
{
url: "https://api2.panopta.com/v2/monitoring_node/41"
hostname: "phoenix01.monitorengine.com"
ip_address: "65.23.158.149"
name: "Phoenix"
textkey: "na.west.phoenix01"
}
I just want to be able to access the name variable from that JSON and pass it through my function. I wanted to at least get the above code to work before I try to figure out how to create an object so I can successfully call the name, something like .append(object.name)
I just started learning JQuery and this is my first post so sorry if I didn't include enough details.
You can't apply ajax calls to other domains. You can make workaround using server-to-server calls via curl() or file_get_content(url), and then make a js call to your script.
First make php file, which will call the server note that if you want to use file_get_contents you should allow_url_fopen in your php.ini:
myProxy.php
<?
$content = file_get_contents($yourUrl);
// do whatever you want with the content then
// echo the content or echo params via json
?>
your js should make call to your PHP, so you have workaround Same Domain Policy:
$.ajax({
url: 'myProxy.php',
type: 'GET',
dataType: 'json',
success: function() { alert('hello!'); },
error: function() { alert('boo!'); },
beforeSend: setHeader
});
});
I am not sure if your api info is correct, but I think the main thing you need to do is change to jsonp instead of json due to the same origin policy that musa mentions.
The following JS fiddle "works" but the request is not authorized at the server: http://jsfiddle.net/cf8S9/.
$(document).ready(function() {
$('#button').click(function(){
$.ajax({
url: 'https://api2.panopta.com/v2/monitoring_node/41',
type: 'GET',
dataType: 'jsonp',
success: function() { alert('hello!'); },
error: function() { console.log(arguments);alert('boo!'); },
beforeSend: setHeader
});
});
function setHeader(xhr) {
//extra stuff from REST CLIENT
xhr.setRequestHeader('Authorization', 'ApiKey nGhhAjGshbOu4dhLYvGY');
} });

creating an array and sending to ajax

I'm trying to gather information from all of the textareas on my page, and then put that information into an array so I can send to the server via ajax/json.
Although I am not quite sure how to go about doing it.
I'm not sure how to pull the information I need from the
Here is what I have so far:
Example of my HTML
"<textarea id='tbObjective_" + counter + "' name='txtObjective' class='objectives' sequence='" + counter + "'></textarea>"
jQuery:
var objectiveList = [];
$('.objectives').each(function (objective) {
objectiveList.push({
id: objective.id,
sequence: objective.sequence,
text: objective.val()
});
});
$.ajax({
type: "POST",
url: url,
dataType: "json",
data: objectiveList
});
Any help would be appreciated
Thanks
you can proceed with the following procedure. i have used python django and html5 for the purpose
1. make a text box which is hidden and after generating your json document set it in this text box (suppose id of textbox is "submit_json") than use
$("#submit_json").val(JSON.stringify(formData, null, '\t')), // (formData, null, '\t') this is js function that i have written for the ourpose
data = JSON.stringify({"jsonDoc":Generated JSON})
console.log(data);
$.ajax({
url: 'http://127.0.0.1:8000/catchjson/',
type: 'POST',
async: false,
contentType: 'application/json',
data: data,
dataType: 'json',
processData: false,
success: function(data){
alert('Done')
//Goto Next Page
},
error: function(jqXHR, textStatus, errorThrown){
alert("Some Error!")
}
})
Now on server you can catch this json if u have problem creating json from your text box let me know
I often use:
var formData = $("form").serialize();
for posting data over ajax, so maybe you could try:
var textareaData = $(".objectives").serialize();
$.ajax({
type: "POST",
url: url,
dataType: "json",
data: textareaData
});
or alternatively make sure all the fields are in a form element and use the first example.
You can parameterise it with $.param(objectiveList)
see jQuery.param()

$.post() behaves different than $.ajax( same paramenters )

I came across something weird, that I want to expose and know if someone as an explanation for it.
Some time back i had a simple post:
$.post("/Route/Save", { myObj: JSON.stringify(myObj), accessToken: getAccessToken()}, function(data)
{
//do stuff
});
and it was working nicely, now doesn't work, and only the accessToken paramenter is correctly received in the route controller
I changed it to:
$.ajax({
url: "/Route/Save",
data: '{ myObj:' + JSON.stringify(myObj) + ',accessToken:"' + getAccessToken()+'"}',
type: 'POST',
datatype: 'JSON',
contentType: 'application/json',
success: function (data)
{
//Do stuff
}
});
And now it works. I'm using firefox 4 and IE9 and believe the reason is connected to the way the browser is sending the info encoded... in the $.post() case it looks like it sends the data as application/x-www-form-urlencoded
I'll be glad to hear from you guys!
Regards,
byte_slave
I'm not sure why it was working before; perhaps a jQuery update changed behaviour?
As to your question on the content-type, $.post is a shorthand wrapper around $.ajax, and from the $.ajax api page, the default value for the contentType is 'application/x-www-form-urlencoded'.
AFAIK, you can't specify the contentType using $.post(). I could be wrong though.
The equivalent with $.ajax should be
$.ajax({
url: "/Route/Save",
data: { myObj: JSON.stringify(myObj), accessToken: getAccessToken()},
type: 'POST',
success: function (data)
{
//Do stuff
}
});