I don't know to set [i] in the array.
statusResponse() {
var dataStatus = this.$.xhrStatus.lastResponse;
for(var i = 0; i < this.maxStatus; i++) {
console.log(this.maxStatus);
console.log([i]);
console.log(dataStatus);
console.log(dataStatus[fs_+ i +_P41001_W41001B]);
this.userInfo.status({
"branch_plant": this.$.xhrStatus.lastResponse.fs_ +
[i] +_P41001_W41001B.data.gridData.rowset[0].sDescription_99.value
});
}
}
You could change:
dataStatus[fs_+ i +_P41001_W41001B]
to
dataStatus["fs_" + i + "_P41001_W41001B"]
Explaination
This is roughly how the computer understands it the following line:
Take string "fs_"
Add the variable i to it, so the string become "fs_4" (if i = 4)
Add "_P41001_W41001B" to it, so the string becomes "fs_4_P41001_W41001B"
Get dataStatus["fs_4_P41001_W41001B"]
Updated code:
statusResponse() {
var dataStatus = this.$.xhrStatus.lastResponse;
for(var i = 0; i < this.maxStatus; i++) {
console.log(this.maxStatus);
console.log([i]);
console.log(dataStatus);
console.log(dataStatus["fs_" + i + "_P41001_W41001B"]);
this.userInfo.status({
"branch_plant": this.$.xhrStatus.lastResponse["fs_" + i + "_P41001_W41001B"].data.gridData.rowset[0].sDescription_99.value
});
}
}
My web API accepts below JSON format (this is input parameter)
[{
"atrSpaUserId": "47fe8af8-0435-401e-9ac2-1586c8d169fe",
"atrSpaClassLegendId": "00D18EECC47E7DF44200011302",
"atrSpaCityDistrictId": "144d0d78-c8eb-48a7-9afb-fceddd55622c"},
{
"atrSpaUserId": "47fe8af8-0435-401e-9ac2-1586c8d169fe",
"atrSpaClassLegendId": "00D18EECC47E7DF44200011302",
"atrSpaCityDistrictId": "144d0d78-c8eb-48a7-9afb-fceddd55622c"
}
]
I am building request below in javascript.
var administratorId = '47fe8af8-0435-401e-9ac2-1586c8d169fe'
var districtId = '144d0d78-c8eb-48a7-9afb-fceddd55622c'
var atrUserLegendsInputs
for (i = 0; i < list.get_items().get_count() ; i++)
{
atrUserLegendsInputs += { atrSpaUserId: administratorId, atrSpaClassLegendId: list.getItem(i).get_value(), atrSpaCityDistrictId: districtId } + ',';
}
atrUserLegendsInputs = atrUserLegendsInputs.substring(0, atrUserLegendsInputs.length - 1);
var legendIds = '[' + atrUserLegendsInputs + ']';
var atrDistrictLegend = { districtID: cityDistrictId, legendIDs: legendIds };
var test = JSON.stringify(atrDistrictLegend);
getting error message:
{["The input was not valid."]}
I am not sure whether I am doing the right way. I am new to Json and ajax calls. Can you one please help me to fix this issue
Try this code
var administratorId = '47fe8af8-0435-401e-9ac2-1586c8d169fe';
var districtId = '144d0d78-c8eb-48a7-9afb-fceddd55622c';
//* create empty array for legends
var atrUserLegendsInputs = [];
for (i = 0; i < list.get_items().get_count() ; i++) {
//* put some values into legends' array
atrUserLegendsInputs.push({
atrSpaUserId: administratorId,
atrSpaClassLegendId: list.getItem(i).get_value(),
atrSpaCityDistrictId: districtId
});
}
var atrDistrictLegend = {
districtID: cityDistrictId,
legendIDs: atrUserLegendsInputs
};
var test = JSON.stringify(atrDistrictLegend);
ANSWERED
Thanks to everyone that has replied on this post. Thanks to Kevin (Best Solution for the loop) and thanks to Deepak for the sort functionality.
I am going to try find a pagination solution for this data on the site, but any further help would be appreciated.
Thanks again all!
ORIGINAL QUIESTION
I am hoping that you can help me out. I have a JSON feed (which I have validated and is working perfectly on http://jsonlint.com/). I have set up the page on my side and I can parse one result no problem. Thing is there are many results in the feed and I need the jQuery to return all the results. The example I am showing here has 11 results, but some of the other pages have up to 300 results. So this is a two part question.
My scripting knowledge is being able to change given code, but writing it myself is not possible (I am in the process of teaching myself though)
How do I return all the results?
How do I paginate the results, say 15 per page?
I am using the Cross Domain Ajax plugin by JAMES PADOLSEY to pull the data - is this the right terminology even?
The jQuery code I am using is:
jQuery.noConflict()(function($) {
$(document).ready(function($) {
$.ajax({
type: 'GET',
url: "http://dealer.mustek.co.za/public-content-api.html?content=dealers&province=limpopo",
success: function(response) {
var headline = $(response.responseText).text()
var json_obj = $.parseJSON(headline); //parse JSON
console.log(json_obj);
var output = '';
for (var i = 0; i < json_obj.user_id; i++)
output += "<div class='dealer'>";
output += "<dl>";
output += "<dt>Company Name</dt>"
output += "<dd>" + json_obj[i].company_name + "</dd>"
output += "<dt>Company Description</dt>"
output += "<dd>" + json_obj[i].company_description + "</dd>";
output += "<dt>Email Address</dt>"
output += "<dd>" + json_obj[i].company_email + "</dd>";
output += "<dt>Contact Number</dt>"
output += "<dd>" + json_obj[i].contact_number + "</dd>";
output += "<dt>Website URL</dt>"
output += "<dd>" + json_obj[i].website_url + "</dd>";
output += "<dt>City</dt>"
output += "<dd>" + json_obj[i].city_suburb + "</dd>";
output += "<dt>Physical Address</dt>"
output += "<dd>" + json_obj[i].physical_address + "</dd>";
output += "</dl>"
output += "<p>"
output += "</div>";
$('#dealer_limpopo').html(output);
},
});
});
});
And I am pulling the div into a test html page http://thegearbox.co/thisisatest/.
As you can see there is no problem with feed, all is working perfectly, just need that pesky line to loop through all the data. Currently the
for (var i = 0; i < json_obj.user_id; i++)
is not doing the job.
Any help would be super appreciated!
PS. is there any way to sort the data alphabetically, or am I just being cheeky asking for so much? :)
UPDATE
A HUGE thank you to everyone that has commented so far. I have used #Kevin's solution below to show all the data using
for (var i = 0; i < json_obj.length; i++)
I am using #Deepak's solution to sort the data alphbetically:
json_obj.sort(function compare(a,b) {
if (a.company_name < b.company_name)
return -1;
if (a.company_name > b.company_name)
return 1;
return 0;
});
Can anyone help with the pagination?
The for loop should iterate once for each item in the [] json_obj. In Javascript an array contains an inherit property length. The value of the length property indicates how many elements are contained within the array. Adding this to for loop tells it to iterate once per element in the array.
Change the loop to:
for (var i = 0; i < json_obj.length; i++){
//code omitted
}
$.ajax({
type: "GET", timeout: 60000, cache: false, dataType: "jsonp", url: strURL + "&callback=?",
success: function (response) {
objAttributes = response.Attributes;
var List = "";
if (objAttributes != null) {
var iLoop = 0;
var xLoop = 0;
for (iLoop = 0; iLoop < objAttributes.Product.length; iLoop++) {
if (List.length > 0) List = List + ":";
List = List + objAttributes.Product[iLoop].ID;
List = List + "_" + objAttributes.Product[iLoop].ITEM;
}
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
This code may help you.
You should use jquery's for-each loop.
if your json response object is an array.
$.each( json_obj, function(index, value) {
// process the value
// append value.company_name, value.company_email etc. to output.
});
And, to sort your data on company name.
json_obj.sort(function compare(a,b) {
if (a.company_name < b.company_name)
return -1;
if (a.company_name > b.company_name)
return 1;
return 0;
});
your "json_obj" is an array.
change
for (var i = 0; i < json_obj.user_id; i++)
to
for (var i = 0; i < json_obj.length; i++) {
Since in your case json_obj seems to be a list so,
json_obj.user_id is undefined.
try this if you have single list.
for (var i = 0; i < json_obj[0].user_id; i++)
or else use
$.each(json_obj,function(data,index){
//your html code here
})
Hope it helps...
Here is a way to sort your data :
json_obj.sort(function (a, b) {
if (a.company_name > b.company_name) { return 1; }
if (a.company_name < b.company_name) { return -1; }
return 0;
});
Then you may replace the for loop with jQuery.map() to get the output :
var output = jQuery.map(json_obj, function (row) {
// build your HTML here
return '<div>' + row.company_name + '</div>';
});
Finally :
$('#dealer_limpopo').html(output.join('')); // don't forget to join :)
"All in one" answer :
var headline = $(response.responseText).text()
var json_obj = $.parseJSON(headline); //parse JSON
json_obj.sort(function (a, b) {
if (a.company_name > b.company_name) { return 1; }
if (a.company_name < b.company_name) { return -1; }
return 0;
});
return jQuery.map(json_obj, function (row) {
return [
'<div class="dealer">',
'<dl>',
'<dt>Company Name</dt>',
'<dd>', row.company_name, '</dd>',
'<dt>Company Description</dt>',
'<dd>', row.company_description, '</dd>',
'<dt>Email Address</dt>',
'<dd>', row.company_email, '</dd>',
'<dt>Contact Number</dt>',
'<dd>', row.contact_number, '</dd>',
'<dt>Website URL</dt>',
'<dd>', row.website_url, '</dd>',
'<dt>City</dt>',
'<dd>', row.city_suburb, '</dd>',
'<dt>Physical Address</dt>',
'<dd>', row.physical_address, '</dd>',
'</dl>',
'</div>'
];
}).join('');
I am trying to get the content from CKEDITOR for every div with the id change (change1, change2, ...)
var data2= CKEDITOR.instances.change1.getData();
for (var i = 2; i <= 30; i++){
if (typeof([\"CKEDITOR.instances.change\"+i]) != 'undefined') {
var edit = CKEDITOR.instances.change[i].getData();
data2 = data2 + '</div><div class=\"d W1 h1\">' + edit;
}}
I've tried it like this but getting error:TypeError: CKEDITOR.instances.change is undefined at
var edit = CKEDITOR.instances.change[i].getData();
Do not use typeof('...') because it will always return the typeof that object which is an object in you case, and then != from undefined...
try this:
if (CKEDITOR.instances['change' + i]) {
// put your code here
}
I am getting an error stating that an object is expected in the below code. The error is:
Object Expected: this.regionalRankings[worldRegion][rankType] = this.getRankings(rankType, this.regionalRankingKey[worldRegion]);
Declarations...
this.regions = {};
this.regions = ["US", "Europe", "Asia"];
this.regionalRankingKey = ["SP500", "GBE", "CNG"]; //this is the ranking model key for pulling up the rankings object.
this.rankingTypes = ["gainers", "losers", "actives"];
this.regionalRankings = {};
this.rankingWSODIssues = [];
marketSummary_data.prototype.initRankingsNew = function(){
for(var worldRegion in this.regions){
for (var rankType in this.rankingTypes){
//this is the line getting the error.
this.regionalRankings[worldRegion][rankType] = this.getRankings(rankType, this.regionalRankingKey[worldRegion]);
for(var i = 0; i < 5; i++){
this.rankingWSODIssues.push(this.regionalRankings[worldRegion][rankType].value("Result[0].Row[" + i + "].WSODIssue"));
}
}
}
for(var item in this.rankingWSODIssues){
Response.Write("<p>" + item + ": " + rankingWSODIssues[item] + "</p>");
}
}
the function this.getRankings returns an object.
marketSummary_data.prototype.getRankings = function(rankingType, rankingSet){
//ranking types Epctchg+ (pct gainers)
//Epctchg- (pct losers)
//Edollar+ (net gainers)
//Edollar- (net losers)
//Evol+ (highest volume)
//rankingSets
if (rankingType == "gainers"){
rankingType = "Epctchg+";
}
if (rankingType == "losers"){
rankingType = "Epctchg-";
}
if (rankingType == "actives"){
rankingType = "Evol+";
}
var rankings = User.CreateObject("WIT.Rankings.1")
rankings.SetVariableName("Rankings")
rankings.SetInput("Ranking.RT", 0)
rankings.SetInput("Ranking.Type", rankingType)
rankings.SetInput("Ranking.Set", rankingSet)
rankings.SetInput("Ranking.Rows", 5)
rankings.SetInput("Ranking.Symbolset", "BridgeStreet");
rankings.SetInput("Ranking.MinPrice", 0); // only want stocks trading higher> 0
rankings.Retrieve();
return rankings;
}
Any ideas on what I am doing wrong here?
The problem is that this.regionalRankings[worldRegion][rankType] requires that this.regionalRankings[worldRegion] be something, however this.regionalRankings is an empty object, so an "Object is Required."
I think what you intended to do is:
for(var worldRegion in this.regions){
this.regionalRankings[worldRegion] = {}; // Make it into an object.
for (var rankType in this.rankingTypes){
this.regionalRankings[worldRegion][rankType] = ...
}
}