Rendering json data into a grid in asp.net mvc - javascript

I am looking to populate my grid with JSON data. The data is in the below format:
[{
"SiteId":"1",
"SiteName":"University of Minessota",
"SiteStatus":"Fully Operational"
},{
"SiteId":"2",
"SiteName":"MSP Airport-Humphrey",
"SiteStatus":"Settlement Required"
},{
"SiteId":"3",
"SiteName":"City Of Minneapolis-Lot C",
"SiteStatus":"Fully Operational"
},{
"SiteId":"4",
"SiteName":"TargetCenter",
"SiteStatus":"Low Tickets"
},{
"SiteId":"5",
"SiteName":"Excel Energy Center",
"SiteStatus":"Out Of Tickets"
}]
and i am passing this to the view using my controller method:
public JsonResult StatusReport()
{
List<CenterStatus> status = MvcList.Models.CenterStatus.GetStatus();
return this.Json(status, JsonRequestBehavior.AllowGet);
}
Now in my view I need to populate this JSON data into a grid:
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "CenterStatus/StatusReport.aspx",
data: "{}",
dataType: "json",
success: function (data) {
for (var i = 0; i < data.d.length; i++) {
$("#GridView1").append("<tr><td>" + data.d[i].siteID + "</td><td>" + data.d[i].siteName + "</td><td>" + data.d[i].siteStatus + "</td></tr>");
}
},
error: function (result) {
alert("Error");
}
});
But I have no luck in achieving my goal so far. Any suggestions?

Do it like this. do not call append in a loop. Set it to a variable and call the html function only once.
success: function (data) {
var row=""
$.each(data,function(index,item){
row+="<tr><td>"+item.SiteName+"</td></tr>";
});
$("#GridView1").html(row);
},
Working sample : http://jsfiddle.net/x76LD/1/

May be you should use just data instead of data.d in your success function.

I'm guessing the url: "CenterStatus/StatusReport.aspx", might have something to do with it. The correct url should probably be:
url: "/CenterStatus/StatusReport"

Related

The Ajax request does not return an answer from the server

I have a code in JS like this:
$.ajax({
url: $("body").data("url") + "/Documents/CheckDoc",
data: {
docID: id
},
dataType: 'text',
}).success(function (json) {
if (json.status) {
if (json.result) { // word template format
window.open($("body").data("url") + '/Case/OpenEnforcementDocument?DocID=' + id + '&RRcode=' + RR);
}
else { //html template format
window.open($("body").data("url") + '/EnforcementPrintout/Printout?DocID=' + id + '&copys=' + copys, "_blank");
}
}
else {
toastr.error(json.message);
}
});
toastr.error("error");
It refers to the CheckDoc function on the server
And there it works great but when it comes back to JavaScript
It does not return to .success and does not reach the last row of the function: toastr.error
Which had to be carried out anyway
It is as if flying from this function and not returning to it again
Someone might know what the problem might be
Will help me a lot
Thank you
It's look like there is some mistake in your code, you closed your code after dataType: 'text', by }) , please try this and let us know:
$.ajax({
type: "POST",
url: $("body").data("url") + "/Documents/CheckDoc",
data: { docID: id },
contentType: "application/json; charset=utf-8",
dataType: 'text',
success: function (json) {
if (json.status) {
if (json.result) { // word template format
window.open($("body").data("url") + '/Case/OpenEnforcementDocument?DocID=' + id + '&RRcode=' + RR);
}
else { //html template format
window.open($("body").data("url") + '/EnforcementPrintout/Printout?DocID=' + id + '&copys=' + copys, "_blank");
}
}
else {
toastr.error(json.message);
}
},
failure: function (response) {
alert("failure");
},
error: function (xhr, ex) {
alert('error')
}
});

JavaScript AutoComplete with php mysql

I have a javascript, it getting json data from data/city.php,, and is working good
var $kUI_autocomplete_template = $('#GJB_city');
if($kUI_autocomplete_template.length) {
$kUI_autocomplete_template.kendoAutoComplete({
minLength: 2,
dataTextField: "city",
template:
'<div class="k-list-wrapper">'+
'<span class="uk-text-muted uk-text-small">#: data.city #</span>' +
'</span>' +
'</div>',
dataSource: {
transport: {
read: {
dataType: "json",
url: "data/city.php"
}
}
},
height: 204
}).data("kendoAutoComplete");
}
now i am trying to get data by posting value to data/city.php?like=value
I need keyup function to get data from city.php as on city.php mysql is using like statement to find data.
I am noob with js so can any one help me with how can i post data and get it working i was trying doing
url: "data/city.php?like=#: data.city #"
its wrong i know can any one please help.
I am using http://demos.telerik.com/kendo-ui/autocomplete/template
dataSource: {
transport: {
read: {
dataType: "json",
url: "data/city.php"
}
}
},
height: 204
}).data("kendoAutoComplete").then(function(value) {
// do someting with data
}, function(reason) {
// console.log(reason);
});
source on developer.mozilla

Ajax call returns some but not all Json data

I'm trying to have the user select some data, which is then inserted into a database using ajax. Then, I use ajax to get the new data from my json endpoint, so that I can update the webpage without reloading it. However, ajax call sometimes doesn't return all the updated data. For example, if the user were to select 3 items, the ajax call sometimes only returns the first 2 items.
Insert into database
$.ajax({
dataType: "json",
url: "http://localhost:8080/api/addChampionForUser",
data: params,
async: false,
success: function (data) {
$.each(data.newChamp, function (key, val) {
if (val.mes) {
$(".message").append("<div> " + val.mes + " </div>");
}
else if (val.err) {
$(".message").append("<div> " + val.err + " </div>");
}
});
}
});
Get info from api
$.ajax({
dataType: "json",
url: "http://localhost:8080/api/getChampions",
data: params,
//have also tried setting async to false
async: true,
success: function(data){
$.each(data.champions, function(key, val){
$.each(val, function(k2, v2){
alert(v2.name + " " + v2.type);
});
});
}
});
The json output looks like this:
{"champions":[[
{
"class":"championkeeper.Champion",
"id":null,
"name":"Aatrox",
"type":"fighter",
"user":"test"
},
{
"class":"championkeeper.Champion",
"id":null,
"name":"Blitzcrank",
"type":"fighter",
"user":"test"
},
{
"class":"championkeeper.Champion",
"id":null,
"name":"Darius",
"type":"fighter",
"user":"test"
}
]]}

Can not seem to pass more than one variable with jquery to mysql

I have seen several examples and can't seem to get the hang of passing more than one variable to mysql using jquery. Here is my situation:
I have a page with 2 cascading drop downs,( they work great using jquery to update second drop down based on the first drop down.)
when the first drop down is selected jquery updates the second drop down AND passes the customer id to a php script that creates a new record in the tblinvoice table (this also works great no problems.)
when the second drop down is selected I need to pass that value along with the invoice number to my php script so I can update the record with the instid.(this is the part that don't work)
If I only pass the instid and manually put the invoice number in the where clause of the query all works fine. If I omit the where clause all records are updated as expected. I need to know what I am doing wrong or what is missing.
I will try to post the code here
jquery code
$(document).ready(function() {
$("select#cust").change(function() {
var cust_id = $("select#cust option:selected").attr(
'value');
var test = $("#test").val();
var din = $("#idate").val();
$("#inst").html("");
if (cust_id.length > 0) {
$.ajax({
type: "POST",
url: "fetch_inst.php",
data: "cust_id=" + cust_id,
cache: false,
beforeSend: function() {
$('#inst').html(
'<img src="loader.gif" alt="" width="24" height="24">'
);
},
success: function(html) {
$("#inst").html(html);
}
});
if (test == 0) {
$.ajax({
type: "POST",
url: "wo_start.php",
data: "cust_id=" + cust_id,
cache: false,
beforeSend: function() {
},
success: function(html) {
$("#invoice").html(html);
$("#test").val(1);
var inum = $("#inv").val();
$("#invnum").val(din +
"-" + inum);
}
});
}
}
});
$("select#inst").change(function() {
var inst_id = $("select#inst option:selected").attr(
'value');
var custid = $("select#cust option:selected").attr(
'value');
var invid = # ("#inv").val()
if (inst_id.length > 0) {
$.ajax({
type: "POST",
url: "wo_start.php",
data: {
inst_id: inst_id,
}
cache: false,
beforeSend: function() {
},
success: function() {
}
});
}
});
});
I have tried using data: {inst_id:inst_id,custid:custid,invid:invid,} (no update to the table like this)
I also tried data: "inst_id="+inst_id+"&custid="+custid+"&invid="+invid,(this also gives no results.)
Can someone PLEASE look at this jquery and see if I am making a simple error?
Try this format:
data: { inst_id: inst_id, custid: custid, invid: invid },
You can post a JSON object to the server so long as you serialize it and then let the server know the data type.
First you need to define your JSON object:
var postData = { inst_id: inst_id, custid: custid, invid: invid };
Then update your ajax to use the serialized version of that object and let the server know the data type:
$.ajax({
type: "POST",
url: "fetch_inst.php",
data: JSON.stringify(postData),
contentType: "application/json",
..continue the rest of your ajax....

"filter" json through ajax (jquery)

I'm trying to filter the json array through ajax and not sure how to do so.
{
posts: [{
"image": "images/bbtv.jpg",
"group": "a"
}, {
"image": "images/grow.jpg",
"group": "b"
}, {
"image": "images/tabs.jpg",
"group": "a"
}, {
"image": "images/bia.jpg",
"group": "b"
}]
}
i want it so that i can only show items in group A or group B.
how would i have to change my ajax to filter through the content?
$.ajax({
type: "GET",
url: "category/all.js",
dataType: "json",
cache: false,
contentType: "application/json",
success: function(data) {
$('#folio').html("<ul/>");
$.each(data.posts, function(i,post){
$('#folio ul').append('<li><div class="boxgrid captionfull"><img src="' + post.image + '" /></div></li>');
});
initBinding();
},
error: function(xhr, status, error) {
alert(xhr.status);
}
});
Also, how can I can I make each link process the filter?
Group A Group B
Sorry for all these questions, can't seem to find a solution..
Any help in the right direction would be appreciated.
Thanks!
You'll need to write a filter function, more than likely:
function filterGroup(obj, filteredGroup) {
var resultObj = $.extend({},obj);
for (var i in obj) {
if ( obj.hasOwnProperty(i) ) {
if ( obj[i].group && obj[i].group !== filteredGroup ) {
delete resultObj[i];
}
}
}
return resultObj;
}
Then you'd just run your data through that filter. You'll also probably want to switch to a POST with a bunch of JSON like this.
$.ajax({
type: "POST",
url: "category/all.js",
dataType: "json",
cache: false,
data: {"posts": filterGroup(posts, 'a')},
contentType: "application/json",
success: function(data) {
$('#folio').html("<ul/>");
$.each(data.posts, function(i,post){
$('#folio ul').append('<li><div class="boxgrid captionfull"><img src="' +
post.image + '" /></div></li>');
});
}
});
Most of this code is hypothetical since I don't know exactly what you're doing, but it should get you close. Just don't expect to be able to copy/paste it. This assumes you actually named your data variable as posts for instance.
To make a link run code, you'll need to attach a click handler and identify each link. I'll assume you added a classname to each (filterA and filterB):
$('.filterA').click(function(){
filterGroup(someDataObject, 'a');
return false;
});
$('.filterB').click(function(){
filterGroup(someDataObject, 'b');
return false;
});

Categories