"filter" json through ajax (jquery) - javascript

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;
});

Related

Importing JSON based remote data to Select2 using AJAX

The aim is to import data from the Controller side to a Select2 element (with multiselect toggled on). I want the setup to look something like the tags box in Stack Overflow, wherein you can begin typing a tag, select it, and select another one later.
I have been using the Select2 documentation as a reference, however the request isn't being sent to the Controller.
Select2 Documentation
My Code:
$(".jsData").select2({
ajax: {
contentType: 'application/json',
url: '<%=Url.Action("GetDataMethod","RelevantController")%>',
type: 'POST',
dataType: 'json',
data: function (term) {
return {
sSearchTerm: term
};
},
results: function (data) {
var datajs = $.map(data, function (obj) {
obj.text = obj.someterm; // desired field,
obj.id = obj.someId;
return obj;
});
return {
results: JSON.parse("[" + datajs.split(",") + "]")
};
}
},
multiple: true
});
I'm relatively new to bringing data dynamically to Select 2, so any help would be most appreciated. Thanks!
UPDATE: Found the solution, posting it here for others.
HTML
<input class="jsData" style="width: 100%" id="select2Data" ></input>
Javascript
$(".jsData").select2({
ajax: {
minimumInputLength: 4,
contentType: 'application/json',
url: '<%=Url.Action("GetData","Controller")%>',
type: 'POST',
dataType: 'json',
data: function (term) {
return {
sSearchTerm: term
};
},
results: function (data) {
return {
results: $.map(JSON.parse(data), function (item) {
return {
text: item.term,
slug: item.slug,
id: item.Id
}
})
};
}
},
multiple: true
});

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"
}
]]}

jsTree - Populate Tree Dynamically using AJAX/C#Web Method

I have a div which I would like to fill with a jsTree:
I get the "Loading" icon where the tree is meant to display, however, there would seem to be a javascript error, even though one is not thrown.
I load my folder structure from an AJAX Request as follows. The Documents.aspx/GetFolders Web Method returns a List containing FolderId, ParentId & Folder Name. I have debugged the web method and it is passing the correct results to the jsTree "data" function.
$.ajax({
type: "POST",
url: 'Documents.aspx/GetFolders',
contentType: "application/json; charset=utf-8",
success: function (data) {
data = data.d;
$("#tree").jstree({
"core": {
"themes": {
"responsive": true
},
"data": function () {
var items = [];
items.push({ 'id': "jstree_0", 'parent': "#", 'text': "Documents" });
$(data).each(function () {
items.push({ 'id': "jstree_" + this.DocumentFolderId, 'parent': "jstree_" + this.ParentId, 'text': "" + this.Name });
});
return items;
}
},
"types": {
"default": {
"icon": "fa fa-folder icon-lg"
},
},
"plugins": ["contextmenu", "dnd", "state", "types"]
});
},
error: function () {
toastr.error('Error', 'Failed to load folders<span class=\"errorText\"><br/>There was a fatal error. Please contact support</span>');
}
});
After debugging the code, it seems the data is being retrieved correctly and is returning the object array as intended.
Is there are any problem with the above (or is there somewhere else I should be looking)? Or is there a better method of achieving its intended purpose?
I think I have finally found the answer! :)
"core": {
"themes": {
"responsive": true
},
"data": {
type: "POST",
url: "Documents.aspx/GetFolders",
contentType: "application/json; charset=utf-8",
success: function (data) {
data.d;
$(data).each(function () {
return { "id": this.id };
});
}
},
}
Server side, you need to return the data in the array format required, i.e:
[{id = "node0", parent = "#", text = "Documents"},
{id = "node1", parent = "node0", text = "Public"},
{id = "node2", parent = "node0", text = "Restricted"}]
Just in case anyone has the "loading..." issue, this format fixed it for me when returning data.
[{"id":"node0", "parent":"#", "text":"Documents"},
{"id":"node1", "parent":"node0", "text":"Public"},
{"id":"node2", "parent":"node0", "text":"Public"}]

Rendering json data into a grid in asp.net mvc

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"

parsing specific values in JSON for ajax

I was given this code earlier but am having a hard time parsing the correct data.
I have the following JSON
{
flavors: [{
"image": "images/bbtv.jpg",
"desc": "BioBusiness.TV",
"id": "1"
}, {
"image": "images/grow.jpg",
"desc": "Grow Staffing",
"id": "2"
}]
}
and I want to only show id:1 or id:2.
I have the following code for Ajax
$.ajax({
type: "POST",
url: "foodservice/all.js",
dataType: "json",
cache: false,
data: {"flavors": filterId(flavors, 'a')},
contentType: "application/json",
success: function(data) {
$('#flavor-detail').html("<div/>");
$.each(data.flavors, function(i,item){
$('#flavor-detail div').append('<ul><li><p>' + item.desc + '</p></li></ul>');
});
}
});
and the following function to filter through the JSON object
function filterId(obj, filteredId) {
var resultObj = $.extend({},obj);
for (var i in obj) {
if ( obj.hasOwnProperty(i) ) {
if ( obj[i].id && obj[i].id !== filteredId ) {
delete obj[i];
}
}
}
return resultObj;
}
However, this code does not return anything.
Can someone tell me what I am missing?
Im pretty new to JSON, Ajax so any help would be greatly appreciated.
Thanks!
Why not just check in the "each" code?
$.each(data.flavors, function(i,item){
if (item.id > 2) return;
$('#flavor-detail div').append('<ul><li><p>' + item.desc + '</p></li></ul>');
});
I changed the following code to make it filterable
$.ajax({
type: "GET",
url: "foodservice/all.js",
dataType: "json",
cache: false,
contentType: "application/json",
success: function(data) {
$('#flavor-detail').html("<div/>");
$.each(data.flavors, function(i, item) {
if (item.id != flavorid) return;
$('#flavor-detail div').append('<ul><li><p>' + item.desc + '</p></li></ul>');
});
}
});
and for each link to change the output,
$('#amare').click(function() {
flavorid = "1";
});
$('#sec').click(function() {
flavorid = "2";
})

Categories