I have tried the following lines of code in jquery
<h5>Marks per Subjects</h5>
<ul id="subjectsMarks">
</ul>
$.ajax({
url: 'index.php?action=fetchStudentIfResultFound',
type: 'POST',
dataType: 'JSON',
...
...
for(i=0; i<data[1].length; i++)
{
$("#subjectsMarks li").html(key[1][i] + ':' + data[1][i]+ "<br/>"+data[1]["Status"]);
}
});
In console data is like
0
:
Object
1
:
Array(4)
0
:
Array(1)
1
:
Array(2)
0
:
Object
Physics
:
"150.00/200"
Status
:
"Pass"
proto
:
Object
1
:
Object
Science
:
"400.00/600"
Status
:
"Pass"
proto
:
Object
...........
I want data in li should look like
Marks per Subjects
Physics: 150.00/200
Status : Pass
Science: 400.00/600
Status: Pass
Please help me !!!
Modify your data from backend and add keys to data as below , it will easy to know where have to loop and don't need to know when to stop
var data: {
student: {
"_id": {
"$id": "5715f58299fbad800100003a"
},
"student_id": 36,
"registration_temp_perm_no": "453654",
"roll_no": "31",
"admission_date": "04/12/2016",
"first_name": "Momin",
"middle_name": "Bashir",
"last_name": "Rather",
"dob": "7/9/1995",
"gender": "Male",
"blood_group": "",
"birth_place": "",
"nationality": "",
"language": "",
"religion": "Islam"...
},
marks: {
subjects: [
{
"Physics": "150.00/200",
"Status": "Pass"
},
{
"Science": "400.00/600",
"Status": "Pass"
}
],
"Total Marks": "550/800",
"Grade": "Ist",
}
}
Try loop using below code
//Without modify json from backend
var allSubjects=data[1][1];
//With modify json from backend
var allSubjects=data[1][1]['Subjects'];
for(var i in allSubjects){
var keysOfObject=Object.Keys(allSubjects[i]);
$("#subjectsMarks li").html(keysOfObject[0] + ':' + allSubjects[i][keysOfObject[0]]+ "<br/>"allSubjects[i]["Status"]);
/* //console.log(allSubjects[i].keysOfObject[0], keysOfObject[0])
console.log(allSubjects[i]);*/
}
2nd version loop
for(var i in allSubjects){
var subject='';
for(var key in allSubjects[i]){
subject=key;
break;
}
//var keysOfObject=//Object.Keys(allSubjects[i]);
$("#subjectsMarks li").html(subject + ':' + allSubjects[i][subject]]+ "<br/>"allSubjects[i]["Status"]);
console.log(allSubjects[i][subject], subject)
}
Related
Whenever I am trying to send a JSON object to server it gives me this particular error.
This is my Javascript code where I send the above JSON object to the action class but getting this error:
error: [object Object] status: parsererror er:SyntaxError: Unexpected end of JSON input
I need to understand what should be my JSON format? Is it OK or are changes required?
function openLOV(obj) {
var requestData = {
objId : "productLOV",
attributes : [ {
label : "URL_ID",
column : "URL_ID",
visible : "N"
}, {
label : "URL",
column : "URL",
visible : "Y"
}],
searchKey : "obj.value",
queryKey : "SQL_GET_PRODUCT",
callback : "cb"
};
var requestJSONData = JSON.stringify(requestData);
alert(requestJSONData);
var encrUrl = crcEncodeUrl("/EPSWeb/util/lovAction.do?mode=init&element="+obj.id);
$.ajax({
type : "POST",
url : encrUrl,
dataType: 'json',
contentType : "application/json",
data : requestJSONData,
success : function(response) {
$("#_lov_modal").remove();
createLOVModal();
$("#lovContent").html(response);
$("#btnLOVModal").click();
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
}
});
}
Its a data issue in the JSON you are sending to server,
in your variable requestData you need to add double quotes to the key fields, that makes the JSON valid. As mentioned below.
var requestData = {
"objId": "productLOV",
"attributes": [{
"label": "URL_ID",
"column": "URL_ID",
"visible": "N"
},{
"label": "URL",
"column": "URL",
"visible": "Y"
}],
"searchKey": "obj.value",
"queryKey": "SQL_GET_PRODUCT",
"callback": "cb"
}
This would work.
I am trying to cancel all my listings on Bitskins, but they have a weird system where each listing is unique, even if its for the same item. Meaning my 88 pages of listings is an absolute pain to remove.
So I thought of going the autohotkey route, but my end goal is to actually use the API to create specific listings. So I wrote a little test script/link.
https://bitskins.com/api/v1/cancel_buy_order/?api_key=myapikey&code=mycode&buy_order_id=995544
It worked. I proceeded to make a html with a javascript linked to it, but to spam the link 8 times a second with a decreasing number of id ultimately did not work. The browser would just crash.
Then I realized I can make a little script and run it on the site.
var id = 995544;
function loop() {
setTimeout(function () {
id--;
$.ajax({
url: '/api/v1/cancel_buy_order',
type: 'post',
data: {
api_key: $('#apiKey').text(),
buy_order_id: id
},
});
loop();
}, 1000);
}
loop();
While this works, it would take me 11.5 days to remove all listings. Partially because the delay is 1 second as opposed to 1000/8. (The api only allows 8 request a second.) But the biggest reason would be because it attempts to remove listings that don't even exist.
What I mean by this is, Each by listing has a random increment after the last one (e.g. 994488 -> 994502 -> 994503 and so on).
I needed a way to find the buy order id, and then use it in the second code I put here.
var id = (function () {
var id = null;
$.ajax({
'async': false,
'global': false,
'url': '/api/v1/get_active_buy_orders',
type: 'get',
data: {
api_key: 'myapikey',
code: 'mycode',
},
dataType: 'json',
success: function (data){
id = data
}
});
return id;
console.log(id);
})();
This thankfully works, but unfortunately it does not parse the
"data" : {
"orders" : [
parts of the JSON.
While I would love not to ask how to parse the JSON on here and find the answer for myself, I'm either googling the wrong thing, or am too dumb to understand how to do it.
So my question is, how would I parse JSON in JQuery?
{
"status" : "success",
"data" : {
"orders" : [
{
"buy_order_id" : 503154,
"market_hash_name" : "P2000 | Pulse (Field-Tested)",
"price" : "0.03",
"suggested_price" : "0.14",
"state" : "LISTED",
"created_at" : 1454390518,
"updated_at" : 1454390518,
"settled_with_item" : null
},
],
"page" : 88
}
}
if you want to get all buy_order_ids from JSON try the following snippet
x = {
"status": "success",
"data": {
"orders": [{
"buy_order_id": 503154,
"market_hash_name": "P2000 | Pulse (Field-Tested)",
"price": "0.03",
"suggested_price": "0.14",
"state": "LISTED",
"created_at": 1454390518,
"updated_at": 1454390518,
"settled_with_item": null
}, {
"buy_order_id": 502154,
"market_hash_name": "P2000 | Pulse (Field-Tested)",
"price": "0.03",
"suggested_price": "0.14",
"state": "LISTED",
"created_at": 1454390518,
"updated_at": 1454390518,
"settled_with_item": null
}, ],
"page": 88
}
}
var ids = x.data.orders.map(function(d) {
return d.buy_order_id
})
document.write('<pre>' + JSON.stringify(ids, 0, 4) + '</pre>')
I'm learning ajax.... I am trying to make a basic request from a json file, which is in the same folder as my index.html, but for some reason it says undefined :( I can see the error is on the variable people, but I can't catch why it's undefined....
html:
<div id="personName"></div>
javascript:
var xhr = new XMLHttpRequest(); //it holds the ajax request
xhr.onreadystatechange = function() { //callback
if(xhr.readyState === 4) {
var people = JSON.parse(xhr.responseText);//it takes the string from the response and it converts it in a javascript object
console.log(people);
for (var i=0; i<people.length; i += 1) {
var htmlCode = "<p>" + people[i].name + "</p>";
}
document.getElementById('personName').innerHTML = htmlCode;
} else {
console.log(xhr.readyState);
}
};
xhr.open('GET', 'addresses.json');
xhr.send();
addresses.json:
{
"people": [
{
"position" : "1",
"name" : "Familia Molina Fernandez",
"streetType" : "C/",
"streetName " : "Nuria",
"streetNumber" : "40",
"floor" : "",
"flat" : "",
"zipCode" : "08202",
"city" : "Sabadell",
"state" : "Barcelona",
"country" : "Spain"
},
{
"position" : "2",
"name" : "Familia Astals Fernandez",
"streetType" : "Avda/",
"streetName " : "Polinya",
"streetNumber" : "61",
"floor" : "1",
"flat" : "1",
"zipCode" : "08202",
"city" : "Sabadell",
"state" : "Barcelona",
"country" : "Spain"
}
]
}
Any ideas?
Cheers!!!!
Try console.log(people); and take a look at the object to which your variable refers. (Hint: it's not what you think it is!)
Your variable people refers to an object with only one attribute named "people". That attribute is an array. So with that JSON structure, your code could be written:
var data = JSON.parse(...)
var people = data.people;
(alternatively, I might redesign the JSON and remove the extra level of indirection: just encode the array itself without wrapping it in an object that contains nothing else)
I'm looking to filter a list of objects in a JSON array when an HTML checkbox is clicked. I know about the JavaScript array.sort() method but how do I eliminate items based on checkbox clicks? Do I need an event listener?
My JSON looks as so:
{ "lots" : [
{
"name" : "Parking Lot Name",
"price" : 2,
"cash" : true,
"credit" : false,
"address" : "1234 W Main Ave",
"center" : {
"lat" : 67.659414,
"lng" : -137.414730
}... etc.
So if I've got a form that includes checkboxes for eliminating parking lots based on payment type, how should I go about implementing that? I've read about a jQuery array.grep() function, is that it?
My page is being built using a JS loop like this:
makeList(){
var self = this;
self.jsonFile = $.ajax({
type: 'GET',
url: 'assets/data/default.json',
dataType: 'json',
success: function(response) {
console.log(response);
}
});
self.jsonFile.done(function(data){
//Sort low to high by default
data.lots.sort(function(a, b){
return(a.price > b.price)
});
for (var i = 0; i < data.lots.length; i++) {
document.getElementById('jsonList').innerHTML +=
'<li>
<div id="text">
<p class="price">
$' + data.lots[i].price + '.00
</p>
<p class="info">' +
data.lots[i].address +
'</p>
</div>
<form method="get">
<button type="submit" formaction="https://www.google.com/maps/dir/Current+Location/' +
data.lots[i].address +
'">Directions
</button>
<button type="submit" formaction="detail-view.html">Details
</button>
</form>
</li>';
}
});
}
You can eliminate like this:
You have to bind a onchange function to checkboxes then use following way to that function
data = [{
"name": "name",
"location1": "no",
"description": "description of services"
},
{
"name": "name2",
"location1": "yes",
"description": "description of services2"
},
{
"name": "name3",
"location1": "no",
"description": "description of services3"
}
];
b = $.grep(data, function(el, i) {
return el.location1.toLowerCase() === "yes"
});
You can get the lots where the payment type is say "cash" using:
var cashLots = data.lots.filter(function(lot){return lot.cash});
as an arrow function:
var cashLots = data.lots.filter(lot => lot.cash);
i have the following Problem. Sorry for my bad english that way.
I want to read a jsonfile and count the Number of Persons in it.
This result i will write to an variable.This variable is connected to the TileContainer. So when i write an new entry in my Json File i want that the TileContainer number is increased to.
Here my Code from my Company.json File:
{
"mitarbeiter": [
{ "Lastname": "Mustermann",
"Firstname": "Max",
"icon": "sap-icon://globe",
"adress": "Essen",
"geschlecht": "männlich",
"plz": "42222",
"street": "Viehoferplatz 11",
"jobinfo": "Softwareentwickler"
},
{ "Lastname": "Fischer",
"Firstname": "Elke",
"icon": "sap-icon://globe",
"adress": "Hamburg",
"geschlecht": "weiblich",
"plz": "31441",
"street": "Am Fischmarkt 12",
"jobinfo": "Verwaltungsassistentin"
},
{ "Lastname": "Mustermann",
"Firstname": "Heike",
"icon": "sap-icon://globe",
"adress": "Essen",
"geschlecht": "weiblich",
"plz": "42222",
"street": "Viehoferplatz 11",
"jobinfo": "Vorstandsvorsitzende"
}
]
}
on my controller.js
onInit: function() {
this.getView().addDelegate({onBeforeShow: function(evt) {
if (this.direction != "back") {
var model = new sap.ui.model.json.JSONModel();
model.loadData("JsonModels/Company.json");
alert(model.getJSON());
var XYZ;
var jsonModel =
{
"Tiles":[
{"Tile":
{ id : "idModelTile1",
title : "Mitarbeiter",
info: "Mitarbeiterdaten",
icon:"sap-icon://company-view",
activeIcon:"inbox",
number: XYZ,
appto: "idListPage"
//numberUnit: "positions"
},
}, ......
I want that the variable XYZ gets the Length Value, bevor the TileContainer is rendered. So the Number of Company-Employess is given on the Selectionscreen View.
Hope some one can help me. I make some implementations with jquery and so but nothing really work fine.
Dear,
Christian
When i add
alert(model.getProperty("/mitarbeiter/length"));
i get the alert message "undefined"...
Since the length property of an array can be read, you could simply use
var XYZ = model.getProperty("/mitarbeiter/length");
EDIT: here's a code example for the comment I gave below
onInit: function() {
jQuery.ajax({
url: "JsonModels/Company.json",
dataType: "json",
success: function(data, textStatus, jqXHR) {
var mitarbeiterCount = data.length;
var oTileModel = new sap.ui.model.json.JSONModel();
oTileModel.setData({
tiles :[{
tile : {
id : "idModelTile1",
title : "Mitarbeiter",
info : "Mitarbeiterdaten",
icon :"sap-icon://company-view",
activeIcon:"inbox",
number : mitarbeiterCount,
appto : "idListPage"
},
}]
});
sap.ui.getCore().setModel(oTileModel);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Oh no, an error occurred");
}
});
}
In your view, if you now bind your tile's number property, it should automagically work:
var oTileTemplate = new sap.m.StandardTile({
icon : "{icon}",
number : "{number}",
numberUnit: "mitarbeiter",
title : "{title}",
info : "{info}"
});
var oTileContainer = new sap.m.TileContainer().bindAggregation("tiles", "/", oTileTemplate);
//Etc...