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";
})
Related
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 + '©s=' + 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 + '©s=' + copys, "_blank");
}
}
else {
toastr.error(json.message);
}
},
failure: function (response) {
alert("failure");
},
error: function (xhr, ex) {
alert('error')
}
});
the jquery Select2(Version: 3.5.4) plugin doesn't show my initial value which I loaded on the initSelection function of the plugin. Here is my code:
$("#materialFieldTags").select2({
tags: true,
initSelection : function (element, callback) {
console.log(element);
console.log(callback);
var countryId = "3"; //Your values that somehow you parsed them
var countryText = "mater3";
var data = [];//Array
var tempJSONMat = {
materials: []
};
$.ajax({
url: "php/FormProcessing.php",
type: "post",
data: "main=" + "materialFault" + "&faultid="+ main.faultId,
dataType: 'json',
success: function(data){
data.forEach(function(column) {
//console.log(column);
tempJSONMat.materials.push({
"id" : column.material_id,
"text" : column.name
});
});
}
});
callback(tempJSONMat.materials[0]);
},
ajax: {
type: "POST",
url: 'php/FormFilling.php',
dataType: 'json',
data: function (params) {
return "main=" + "allMaterials" + "&searchterm=" + params;
},
processResults: function (data, page) {
return {
results: $.map(data, function (item) {
return {
text: item.name,
id: item.id
};
})
};
},
cache: true
}
});
Can you take I look at my code? Because I can't see it!! I also have try the:
$("#materialFieldTags").select2("data",mydata);
After the initialization of the plugin, but I am getting the same result.
Finally, I found my mistake! It was define two element by the same id, by mistake! The data appeared on first one and I was looking the second one.
I have tried searching all possible matches of my problem and also have tried a couple of solutions but unfortunately none worked
My backend code:
Person p;
foreach(DataRow dr in dt.Rows)
{
p = new Person();
p.id = Convert.ToInt16(dr["Id"]);
p.name = dr["Name"].ToString();
p.phone = Convert.ToInt64(dr["Phone"]);
pList.Add(p);
}
string ans = JsonConvert.SerializeObject(pList, Formatting.Indented);
jQuery.ajax
function ShowData() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/Data",
data: "{}",
dataType: "json",
success: function (data) {
alert(data.d);
var list = { "Person": +data };
for (i = 0; i < list.Person.length; i++) {
alert('Id: ' + list.Person[i].Id + '/nName: ' + list.Person[i].Name + '/nPhone: ' + list.Person[i].Phone);
console.log('Id: ' + list.Person[i].Id + '/nName: ' + list.Person[i].Name + '/nPhone: ' + list.Person[i].Phone);
}
console.log(list.Person.length);
},
error: function (result) {
alert("Error");
}
});
}
Alert output
[
{
"id": 1,
"name": "Bhavik",
"phone": 9601109585
},
{
"id": 2,
"name": "Xyz",
"phone": 1234567890
},
{
"id": 3,
"name": "Abc",
"phone": 9876543210
}
]
console.log(list.Person.length); returns undefined and hence does not enters the for loop.. So to work out with it.. and why is it necessary to specify contentType while dataType already exist.. Also can I use $.getJSON instead of $.ajax.
You should change your code to be var list = {"Person": data.d}; to reflect what you're alerting.
function ShowData() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/Data",
data: "{}",
dataType: "json",
success: function (data) {
alert(data.d);
var list = { "Person": +data.d };
for (i = 0; i < list.Person.length; i++) {
alert('Id: ' + list.Person[i].Id + '/nName: ' + list.Person[i].Name + '/nPhone: ' + list.Person[i].Phone);
console.log('Id: ' + list.Person[i].Id + '/nName: ' + list.Person[i].Name + '/nPhone: ' + list.Person[i].Phone);
}
console.log(list.Person.length);
},
error: function (result) {
alert("Error");
}
});
}
Also this should be a GET request not a post, then you would be able to use $.getJSON.
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"
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;
});