Help with php/javascript loading json file and using json data in page

I have a dashboard where I want to update data every 3 seconds. Instead of many users polling the database every 3 seconds for each instance of the dashboard app I want to export the query results to a json file. The dashboard app will read the json file and use the contents within the dashboard. I need help with the code to create the class to read and parse the json file and use the data within the dashboard page.

Below is the dashboard index.html page where I need to read the file current_members.json and update the value <div class="metric">1794</div> with the json file data:
<!DOCTYPE html>
<?php require_once("inc/init.php"); 
$report = new Report();
?>
<html lang="en">
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta charset="utf-8">
    <title>Dashboard</title>
    <meta name="kpi viewport" content="width=device-width, initial-scale=1.0">
</head>
<body class="black">
	<div class="cf-container cf-nav-active">
		<div class="col-sm-2 cf-item">
			<div class="row">
				<div class="inner">
					<header>
						<p><span></span>Current Members</p>
					</header>
					<div class="content">
						<div class="cf-svmc">
							<div class="metric">1794</div>
							<div class="change m-green metric-small">
								<div class="arrow-up"></div>
								<span class="large">12<span class="small">.35%</span></span>
							</div>
						</div> <!-- //end cf-item -->										
					</div> <!-- // end row -->	
				</div> <!-- // end inner -->	
			</div> <!-- // end row -->
		</div> <!-- //end col -->
	</div> <!-- //end container -->
</body>
</html>

Open in new window


current_members.json file contains the below and is created using a perl script and is updated every 3 seconds:
[{"current_members":"1752"}]

Open in new window


below is where I have started to create a class file init.php to return the json data via a function and run this function every 3 seconds, This is where I need help in how to read the json file and put the results into a variable to be returned to the index.html dashboard page:
<?php

class Report extends Db {
	public function __construct(){
		//$this->db = new 
		parent::__construct();
	}

// set a timer to run json retrieve function every 3 seconds
	setInterval(function(){autoship_members()},3000)
	
// get json data
	public function current_members()
	{
		return //json data
	}
}

Open in new window


I'm looking for someone to help me with specific code to get this working, I have read several posts on using json and decoding the contents with no better understanding.
DalexanAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

hieloCommented:
>>// set a timer to run json retrieve function every 3 seconds
>>      setInterval(function(){autoship_members()},3000)
This is something that needs to be done on the client-side via javascript, not via php (which runs on the server-side).
<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta charset="utf-8">
    <title>Dashboard</title>
    <meta name="kpi viewport" content="width=device-width, initial-scale=1.0">

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
        setInterval( fetchData, 3000);
});

function fetchData(){
   $.getJSON( "current_members.json", function( data ) {
      $('.metric').html(data[0].current_members);
   });
}

</script>
</head>
<body class="black">
	<div class="cf-container cf-nav-active">
		<div class="col-sm-2 cf-item">
			<div class="row">
				<div class="inner">
					<header>
						<p><span></span>Current Members</p>
					</header>
					<div class="content">
						<div class="cf-svmc">
							<div class="metric">1794</div>
							<div class="change m-green metric-small">
								<div class="arrow-up"></div>
								<span class="large">12<span class="small">.35%</span></span>
							</div>
						</div> <!-- //end cf-item -->										
					</div> <!-- // end row -->	
				</div> <!-- // end inner -->	
			</div> <!-- // end row -->
		</div> <!-- //end col -->
	</div> <!-- //end container -->
</body>
</html>

Open in new window

0
DalexanAuthor Commented:
Thanks hielo, I think I'm close to figuring this out, no need for a class with what I'm doing. In the below im using jquery .getJSON but im unsure on how to append the result to the div.

$("#autoship_members").append(field + " ");

I want to pass the value from the json data corresponding to the current_members

[{"current_members":"1752"}]

<!DOCTYPE html>
<?php require_once("inc/init.php"); 
?>
<html lang="en">
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta charset="utf-8">
    <title>Dashboard</title>
    <meta name="kpi viewport" content="width=device-width, initial-scale=1.0">
	<script>
		// set a timer to run json retrieve function
		setInterval(function(){current_members()},3000)
	</script>
</head>
<body class="black">
	<div class="cf-container cf-nav-active">
		<div class="col-sm-2 cf-item">
			<div class="row">
				<div class="inner">
					<header>
						<p><span></span>Current Members</p>
					</header>
					<div class="content">
						<div class="cf-svmc">
							<div id="current_members" class="metric">----</div>
							<div class="change m-green metric-small">
								<div class="arrow-up"></div>
								<span class="large">12<span class="small">.35%</span></span>
							</div>
						</div> <!-- //end cf-item -->										
					</div> <!-- // end row -->	
				</div> <!-- // end inner -->	
			</div> <!-- // end row -->
		</div> <!-- //end col -->
	</div> <!-- //end container -->
(function(current_members) {    
	$.getJSON("data/current_members.json", function(result){
        $.each(result, function(i, field){
            $("#autoship_members").append(field + " ");
        });
    });
})();
</body>
</html>

Open in new window

0
hieloCommented:
read the comments in the code:
<!DOCTYPE html>
<?php require_once("inc/init.php"); 
?>
<html lang="en">
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta charset="utf-8">
    <title>Dashboard</title>
    <meta name="kpi viewport" content="width=device-width, initial-scale=1.0">
</head>
<body class="black">
	<div class="cf-container cf-nav-active">
		<div class="col-sm-2 cf-item">
			<div class="row">
				<div class="inner">
					<header>
						<p><span>Current Members</span></p>
					</header>
					<div class="content">
						<div class="cf-svmc">
							<div id="current_members" class="metric">----</div>
							<div class="change m-green metric-small">
								<div class="arrow-up"></div>
								<span class="large">12<span class="small">.35%</span></span>
							</div>
						</div> <!-- //end cf-item -->										
					</div> <!-- // end row -->	
				</div> <!-- // end inner -->	
			</div> <!-- // end row -->
		</div> <!-- //end col -->
	</div> <!-- //end container -->

	<script type="text/javascript">
		
		function current_members() {    
			$.getJSON("data/current_members.json", function(result){
				// here, `result` is an array of objects - ex:
				//		[
				//			{"current_members":"323"}
				//			,{"current_members":"3423"}
				//			,{"current_members":"6547"}
				//		]
				// Notice that each object in your array has a `key` 
				// named "current_members".  On every iteration, you need to
				// use that key to 'extract' the value from the object.  Hence
				// the reason I used field.current_members in the argument to
				// append()
        		$.each(result, function(i, field){
					// your html has no element with:
					//		id="autoship_members", but I do see "current_members"
            		$("#current_members").append(field.current_members + " ");
        		});
			});
		}
		
		// fetch json immediately
		current_members();

		// set a timer to run json retrieve function
		setInterval( current_members ,3000);
	</script>

</body>
</html>

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

Slick812Commented:
greetings Dalexan, , I fail to understand the code in your comment  ID: 40812682

I could not find anything in your HTML (a <div> I guess?) with the ID of "autoship_members"  that you use here-
      $("#autoship_members").append(field + " ");

and you say that the JSON text is like this -
       [{"current_members":"1752"}]

which I can not understand you have this code for -
   .append(field + " ");

So I maybe can offer suggestions, but I do not understand the final goal you need in the -
    <div id="current_members" class="metric">----</div>

is this a SINGLE value like
   <div id="current_members" class="metric">1753</div>

or some sort of list like -
   <div id="current_members" class="metric">1751, 1752, 1753, 1754</div>

or other desired result?
0
hieloCommented:
BTW: On my last post (and last reply you supplied), you are missing the statement that imports jquery:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

Open in new window


Copy and paste my previous post onto a new file named "hielo-test.php".  Then before the </head>, add the script tag above to import jquery, then try it out.

Regards,
Hielo
0
DalexanAuthor Commented:
@slick812

Single value
0
hieloCommented:
For a single value, all you need is what I gave you in my first post.  No need to use $.each.

function current_members() {    
	$.getJSON("data/current_members.json", function(result){
		$("#current_members").html( result[0].current_members );
	});
}

Open in new window

0
DalexanAuthor Commented:
Thank you hielo, Also what if I want to replace the value instead of appending the value. Currently every 3 seconds the value in the div is appended ie 1372 1372 1372 1372 and so on ..... I just want the number to be replaced...
0
hieloCommented:
On the last post I used html() instead of append(), which should replace what is already in the div:
 $("#current_members").html(...)

Open in new window

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.