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('');
Related
I have two arrays and need to write the data from both to two columns of a table. At this point I can write correctly data from the first array only and when I want to add the second array data, it gets added into rows.
orderGelen and userNameArr are my arrays. Here you can see my code:
for(let data of orderGelen){
dataHtmlIds += `<tr><td>${data}</td>`;
}
for(let usr of userNameArr){
dataHtmlUsr += `<td>${usr}</td></tr>`;
}
dataHtml = dataHtmlIds + dataHtmlUsr;
console.log(dataHtml);
And here I write that to table:
function tableConfig() {
tableBody.innerHTML = dataHtml;
}
How can I make the second column userNameArr data?
Try to put two arrays in one array like this
const all = orderGelen.map((item, index) => ({ id: item, username: userNameArr[index] }));
let html = '<table>';
for (let row of all) {
html += `<tr><td>${row.id}</td><td>${row.username}</td></tr>`;
}
html+='</table>'
console.log(html);
you could do something like
var dataHtml = "";
for (
let i = 0, j = 0;
i < userNameArr.length || j < orderGelen.length;
i++, j++
) {
dataHtml += `<tr>`;
dataHtml += `<td>${userNameArr[i] ? userNameArr[i] : ""}</td>`;
dataHtml += `<td>${orderGelen[j] ? orderGelen[j] : ""}</td>`;
dataHtml += `</tr>`;
}
and you could write to the table like
function tableConfig() {
tableBody.innerHTML = dataHtml;
}
Hope this helps
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
});
}
}
Display only new updates of JSON data, iterated with each value item in its own paragraph tag using jQuery/javascript.
If each item in the array inside the info key already is outputted in its own <p> tag; do not continue the loop but wait until there is a new item.
This is my JSON:
{
"info": [
"Hello world,",
"how are you doin?",
"Its not going to well for me unfortunately."
]
}
With this jQuery script:
function updatelog() {
$.getJSON("/static/_info",
function(data) {
$.each(data, function(key, item) {
var value = "";
var i;
for (i = 0; i < item.length; i++) {
value += item[i];
$("div").add('<p>' + value + '</p>').appendTo(document.body);
}
});
});
}
var interval = window.setInterval(updatelog, 2000);
With this I get all the items but it doesn't stop iterating. I have searched the interwebs so much that my enter key has lost all hope for salvation. I guess this is pretty easy, but I'm a beginner and also not a javascript coder and i'm ready to pull my hair off. Thanks in advance.
You could take text of all p elements and push it to new array and then check if it includes values from your object
var data = JSON.parse('{"info":["Hello world,","how are you doin?","Its not going to well for me unfortunately."]}'),
pText = [];
$('p').each(function() {
pText.push($(this).text());
});
data.info.forEach(function(el) {
if (!pText.includes(el)) {
$('body').append('<p>' + el + '</p>');
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Hello world,</p>
You can generate a hash from every list-item and use it as id in the div elements. Everytime you retrieve the data you check if the corresponding id exists. If it exists then the item is already present in your page so you don't have to append it again.
function updatelog() {
$.getJSON("/static/_info",
function(data) {
$.each(data, function(key, item) {
var i;
for (i = 0; i < item.length; i++) {
var value = item[i];
var hashCode = value.hashCode();
if(!$("body").find("#" + hashCode).length){
$("div")
.attr("id", hashCode)
.add('<p>' + value + '</p>')
.appendTo(document.body);
}
}
});
});
}
var interval = window.setInterval(updatelog, 2000);
You can use this implementation for the hashCode function.
Generate a Hash from string in Javascript/jQuery
String.prototype.hashCode = function() {
var hash = 0, i, chr, len;
if (this.length === 0) return hash;
for (i = 0, len = this.length; i < len; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
I'm very new in javascript and I try to find problem for a week.
My example code like below (all are in a html page in head tag)
//example function 1
function randomString(len, charSet) {
charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var randomString = '';
for (var i = 0; i < len; i++) {
var randomPoz = Math.floor(Math.random() * charSet.length);
randomString += charSet.substring(randomPoz,randomPoz+1);
}
return randomString;
}
//example function 2
function tests(randomString) {
alert(randomString);
}
//example function 3 pull data from JSON to div id test
$(document).ready(function() {
$.getJSON("http://www.test.com/get_json_data.php?", {
cat_id: "3",
type:'GET',
dataType: 'json',
}, function(data) {
$.each(data.items, function(i, item) {
$('#test').append('<img src="http://www.test.com/images/'+item.image+'"/>');
if (i == 10) return false;
});
});
});
My Problem is I wan to insert var from JSON for example "item.id" in to "onclick" what's I tried to do is below
onclick="tests(randomString(5)+item.id)"
the result I wan to see is alert 5 random chars and include item.id at the end for example
xIyax33 (33 is item.id)
TwQpu34 (34 is item.id)
AERim35 (35 is item.id)
But always show error "item is not defined"
How can I change the code to insert var from JSON ?
You need to add one more parameter in your randomString() function called id which will fetch the item.id. And you need to append it to your randomString.
function randomString(len,id, charSet) {//See second param
charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var randomString = '';
for (var i = 0; i < len; i++) {
var randomPoz = Math.floor(Math.random() * charSet.length);
randomString += charSet.substring(randomPoz, randomPoz + 1);
}
return randomString+id; //+id
}
And change your append to
$('#test').append('<img src="http://www.test.com/images/'+item.image+'"/>');
I currently POST to my script:
process : edit
r1_person : 00008
r2_person : 00009
persons : 2
Which my script accepts:
if (process == 'edit') {
var persons_array = [];
for (i = 0; i < persons; i++) {
var test_push = pnvl(request.getParameter('r' + i + '_person'))
persons_array.push(test_push);
response.write(persons_array[i] + '\n');
}
}
I get back:
undefined
undefined
Where am I going wrong?
EDIT:
Solution: response.write() will not return correctly inside a for loop.
Try this:
pnvl(request.getParameter(eval('r' + i + '_person')))
you iterate from 0 to 1, you want this:
for(i = 1; i <= persons; i++)