Load more json data onClick - javascript

I have been trying to create a webpage that appends JSON data into a ul. The problem is that the JSON file has more than 600 values.
I would like to limit the number of values retrieved, say 10 and then add a 'load more' button to append more, eg. 10 more, to it and so on. Here's my code.
<body onload="loadUser(20)">
<ul id="placeholder"></ul>
function loadUser(arg) {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'people.json', true);
xhr.onload = function() {
if (this.status == 200) {
var users = JSON.parse(this.responseText);
for (var i = 0; i < arg; i++) {
var output = `<li class="list_item">${users[i].name</li>`;
document.getElementById('placeholder').innerHTML += output;
}
document.getElementById('placeholder').innerHTML += '<button onclick="loadmore()">load more</button>';
}
}
xhr.send();
}
// JSON Example:
[{
"id": 1,
"name": "Mithu Mondal",
"email": "mithu#bla.com"
},
{
"id": 2,
"name": "Frankenstien",
"email": "frank#gmail.com"
}
]
Here's the link: https://www.mithuation.ml/jsonExample/
Thanks in Advance.

When you perform an AJAX request (XMLHTTPRequest) it loads the entire file. There is no way to have the browser load a partial file.
If you do not plan to use a database (which would allow you to query a certain number of items at a time), I recommend that you split your data up into several JSON files. When you perform the XMLHTTPRequest, you will only retrieve a subset of the data. For the next request, you will retrieve the next file and thus get the next set of data.

I guess this is what you are searching for Lazy.js. It will parse as much of the JSON as possible, asynchronously.
Import the libraries:
<script type="text/javascript" src="lazy.js"></script>
<!-- optional: if you want support for DOM event and AJAX-based sequences: -->
<script type="text/javascript" src="lazy.browser.js"></script>
If your want to retrieve 10 item at a time:
var response = JSON.parse(this.responseText);
var result = Lazy(response)
.take(10);
document.getElementById('placeholder').innerHTML += output;

Related

Is it possible to post using node red to a page with it's own post?

Effectively trying to use an API called things.io - Currently I am using hard coded inputs on the php page my nodered is being posted to to send an XMLHTTPRequest to the apis network (just to make sure it wasn't my inputs that were at fault).
If I go to the web page directly it will successfully make a call to the api and log it on their platform, so that part of the code seems to be working correctly.
However if I do an XMLHTTPRequest to the same page, no errors will be thrown - but it also won't make the successful call to the API. I can see the content of my page in the debug area, it just doesn't make that call.
Fairly new at node red so sorry for any stupid mistakes, code is below:
<script>
window.onload = function(){
var test = "<?php echo htmlspecialchars($_GET["name"]) ?>";
var temperature = test.substring(test.indexOf("ID: 1, Temperature: ")+20, test.indexOf("*C"));
var humidity = test.substring(test.indexOf("Humidity")+10, test.indexOf("%"));
var data = JSON.stringify({
"values": [
{
"key": "temperature",
"value": 17
},
{
"key": "humidity",
"value": 34
}
]
});
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open("POST", "https://api.thethings.io/v2/things/ /* this is being censored sorry :P /* ?store=true");
xhr.send(data);
}
</script>
Ok Made an answer to this by just skipping this part of the code - Took the original messege - sent it to a nodeRed function
var temperature = msg.payload.substring(msg.payload.indexOf("ID: 1, Temperature:
")+20, msg.payload.indexOf("*C"));
var humidity = msg.payload.substring(msg.payload.indexOf("Humidity")+10, msg.payload.indexOf("%"));
msg.payload = {"values":[{"key":"temperature","value":temperature},{"key":"humidity","value":humidity}]};
msg.headers = {'content-type':'application/json'};
return msg;
Then sent that to the main address.

sending post request javascript

I'm working on an application that should be sending a post request to an internal page that does a certain calculation
When pressing a button, the page(dashboard.php) prints the content of the other page(calculate_salary.php)
here's my js code so far:
<script language="JavaScript" type="text/javascript">
function getXmlHttpRequestObject() {
return new XMLHttpRequest();
}
var receiveReq = getXmlHttpRequestObject();
function sayHello() {
if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
var start_date = $("#start_date").val();
var end_date = $("#end_date").val();
receiveReq.open("GET", 'calculate_salary.php', true);
receiveReq.onreadystatechange = handleSayHello;
receiveReq.send(null);
}
}
function handleSayHello() {
if (receiveReq.readyState == 4) {
document.getElementById('span_result').innerHTML = receiveReq.responseText;
}
}
</script>
I want to send over the values in start_date and end_date to the calculate_salary.php page
I will use that calculate page to perform some sql statements and return the result back.
How can I create this request?
POST is not an absolute necessity, I'm willing to use other techniques (js, php) to get the job done
thanks
You can use ajax instead
$.ajax({
url:"calculate_salary.php",
type:"POST",
data:{
start_date = $("#start_date").val(),
end_date = $("#end_date").val()
},
success:function(response){
$('#span_result').html(response);
}
});
You can read more about $.ajax and $.post
You have to generate querystring with url like so:
var url = 'calculate_salary.php?start_date='+start_date+'&end_date='+end_date;
receiveReq.open("POST", url, true);
Because you are not sending values that is why you are not receiving values on server side.
Another example you can find here:
How do I pass along variables with XMLHTTPRequest
Also check into this:
http://devzone.co.in/jquery-serialize-function-ajax-post-bigger-html-forms/

Accessing a JSON object from an API with AJAX and JavaScript

I'm trying to use AJAX for a simple project I am building using a RESTful API. I want get some data from the API which has a list of people and I want to output that list onto a HTML page.
My XHR object seems to work fine because I made it log the string to the console, it's just accessing the data which is in a nested JSON object that is baffling me. I want to loop through the object and get the name of the person and out it as a <li> item.
Here is the JSON file (from http://api.pmg.org.za/member/):
{
count: 505,
results: [
{
bio: "",
pa_link: "/person/xxxxx-xxxxxx/",
house_id: 3,
name: "xxxxxxx",
url: "http://api.pmg.org.za/member/121/",
house: {
name_short: "NA",
id: 3,
name: "xxxxxxx"
},
start_date: "2013-04-09",
current: true,
profile_pic_url: "http://xxxxxxxxxxx.jpg",
party_id: 1,
pa_url: "http://www.xxxxxxxxx/",
party: {
id: 1,
name: "xxx"
},
// more...
},
// more...
]
}
And my script to access the JSON object:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>PMG API experimentation</title>
</head>
<body>
<div id="members"></div>
<script type="text/javascript">
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
//console.log(xhr.responseText);
var parlyMembers = JSON.parse(xhr.responseText);
var membersHTML = '<ul class="members">';
for (var i = 0; i < parlyMembers.length; i++) {
membersHTML += '<li>'
membersHTML += parlyMembers.results[i].name;
membersHTML += '</li>'
}
membersHTML += '</ul>';
document.getElementById('members').innerHTML = membersHTML;
};
};
xhr.open('GET', 'http://api.pmg.org.za/member/');
xhr.send();
</script>
</body>
</html>
I have a feeling that my JSON query is wrong somehow. Please help.
You are getting the length from parlyMembers in your for-loop, but looping over parlyMembers.results. You need the check the length of the node you are iterating over.
for (var i = 0; i < parlyMembers.results.length; i++) {
membersHTML += '<li>'
membersHTML += parlyMembers.results[i].name;
membersHTML += '</li>'
}
Your JSON string is not okay, please verify it here and correct it.
http://jsonlint.com/
To access the json data in javascript.
var javascript_object = JSON.parse(json_string);
console.log(javascript_object);
you can see complete object, and you can access the variable accordingly.
Thanks
Amit

fetching xml data into a div via ajax and javascript

Building a chat app and I am trying to fetch all logged in user into a div with ID name "chat_members". But nothing shows up in the div and I have verified that the xml file structure is correct but the javascript i'm using alongside ajax isn't just working.
I think the problem is around the area of the code where I'm trying to spool out the xml data in the for loop.
XML data sample:
<member>
<user id="1">Ken Sam</user>
<user id="2">Andy James</user>
</member>
Javascript
<script language="javascript">
// JavaScript Document
var getMember = XmlHttpRequestObject();
var lastMsg = 0;
var mTimer;
function startChat() {
getOnlineMembers();
}
// Checking if XMLHttpRequest object exist in user browser
function XmlHttpRequestObject(){
if(window.XMLHttpRequest){
return new XMLHttpRequest();
}
else if(window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
} else{
//alert("Status: Unable to launch Chat Object. Consider upgrading your browser.");
document.getElementById("ajax_status").innerHTML = "Status: Unable to launch Chat Object. Consider upgrading your browser.";
}
}
function getOnlineMembers(){
if(getMember.readyState == 4 || getMember.readyState == 0){
getMember.open("GET", "get_chat.php?get_member", true);
getMember.onreadystatechange = memberReceivedHandler;
getMember.send(null);
}else{
// if the connection is busy, try again after one second
setTimeout('getOnlineMembers()', 1000);
}
}
function memberReceivedHandler(){
if(getMember.readyState == 4){
if(getMember.status == 200){
var chat_members_div = document.getElementById('chat_members');
var xmldoc = getMember.responseXML;
var members_nodes = xmldoc.getElementsByTagName("member");
var n_members = members_nodes.length;
for (i = 0; i < n_members; i++) {
chat_members_div.innerHTML += '<p>' + members_nodes[i].childNodes.nodeValue + '</p>';
chat_members_div.scrollTop = chat_members_div.scrollHeight;
}
mTimer = setTimeout('getOnlineMembers();',2000); //Refresh our chat members in 2 seconds
}
}
}
</script>
HTML page
<body onLoad="javascript:startChat();">
<!--- START: Div displaying all online members --->
<div id="chat_members">
</div>
<!---END: Div displaying all online members --->
</body>
I'm new to ajax and would really appreciate getting help with this.
Thanks!
To troubleshoot this:
-- Use an HTTP analyzer like HTTP Fiddler. Take a look at the communication -- is your page calling the server and getting the code that you want back, correctly, and not some type of HTTP error?
-- Check your IF statements, and make sure they're bracketed correctly. When I see:
if(getMember.readyState == 4 || getMember.readyState == 0){
I see confusion. It should be:
if( (getMember.readyState == 4) || (getMember.readyState == 0)){
It might not make a difference, but it's good to be absolutely sure.
-- Put some kind of check in your javascript clauses after the IF to make sure program flow is executing properly. If you don't have a debugger, just stick an alert box in there.
You must send the xmlhttp request before checking the response status:
function getOnlineMembers(){
getMember.open("GET", "get_chat.php?get_member", true);
getMember.onreadystatechange = memberReceivedHandler;
getMember.timeout = 1000; //set timeout for xmlhttp request
getMember.ontimeout = memberTimeoutHandler;
getMember.send(null);
}
function memberTimeoutHandler(){
getMember.abort(); //abort the timedout xmlhttprequest
setTimeout(function(){getOnlineMembers()}, 2000);
}
function memberReceivedHandler(){
if(getMember.readyState == 4 && getMember.status == 200){
var chat_members_div = document.getElementById('chat_members');
var xmldoc = getMember.responseXML;
var members_nodes = xmldoc.documentElement.getElementsByTagName("member");
var n_members = members_nodes.length;
for (i = 0; i < n_members; i++) {
chat_members_div.innerHTML += '<p>' + members_nodes[i].childNodes.nodeValue + '</p>';
chat_members_div.scrollTop = chat_members_div.scrollHeight;
}
mTimer = setTimeout('getOnlineMembers();',2000); //Refresh our chat members in 2 seconds
}
}
To prevent caching response you can try:
getMember.open("GET", "get_chat.php?get_member&t=" + Math.random(), true);
Check the responseXML is not empty by:
console.log(responseXML);
Also you might need to select the root node of the xml response before selecting childNodes:
var members_nodes = xmldoc.documentElement.getElementsByTagName("member"); //documentElement selects the root node of the xml document
hope this helps

delay in dynamic loading of external Javascript(JSON) file for Phonegap

im trying to load a external js (json) file (PhoneGap app) whose structure is like
var localString ={
"tag1": "Username",
"tag2": "Password",
"submit": "Submit"
}
and using the below code to load it at runtime, the newlocale variable holds the name of the file to be loaded for eg: if locale is english-USA then var resourcePath = en-US.js. The issue is the first time i run this code i get this error "ReferenceError: localstring is not defined" , but it loads the external strings the second time i load it. In between i am calling the external file using "select" tag in html5. Can someone provide some insights on where im going wrong or any pointers to overcome this issue.
var newlocale = window.DeviceCulture.get();
local(newlocale);
function local(lang) {
try {
var resourcePath = lang + '.js';
var scriptEl = document.createElement('script');
scriptEl.type = 'text/javascript';
scriptEl.src = resourcePath;
alert(resourcePath);
document.getElementsByTagName("head")[0].appendChild(scriptEl);
//$('head').append(scriptEl);
//var localString = window.localString;
document.getElementById("07").value = localString['submit'];
} catch (e) {
errorEvent(e);
}
}
Okay I believe the root cause of your problem is that you are appending the tag for the .js file into the head after the page is already loaded. When you first load a page the script tages are downloaded and interpreted in order so b can depend on a. However, the way you are doing it is non-blocking so that the script you load is not fully loaded by the time you get to the next line in your code which tries to access "localString".
To solve this I'd restructure your code somewhat. First forget about making local files JavaScript. Just make them plain text .json files. For example:
{
"tag1": "Username",
"tag2": "Password",
"submit": "Submit"
}
Then I'd load that file using XHR instead of script tag insertion. Something like:
var newlocale = window.DeviceCulture.get();
var localString;
local(newlocale);
function local(lang) {
try {
var resourcePath = lang + '.json';
var request = new XMLHttpRequest();
request.open("GET", resourcePath, true);
request.onreadystatechange = function(){
if (request.readyState == 4) {
if (request.status == 200 || request.status == 0) {
localString = JSON.parse(request.responseText);
// at this point localString is loaded with the new language
document.getElementById("07").value = localString['submit'];
}
}
}
request.send();
} catch (e) {
errorEvent(e);
}
}
and that should take care of things.

Categories

Resources