How to refresh page elements with jQuery, json, and php

I’m trying to refresh several sections of a page every 10 seconds or so with data being pulled from a php file. I think I’m close but I’m getting this error: ReferenceError: Can’t find variable: a

here is what I have so far:

$a = "some a data...";
$b = "some b data...";
$c = "some c data...";

$data['a'] = $a;
$data['b'] = $b;
$data['c'] = $c;
echo json_encode($data);

<script type="text/javascript">
	$(document).ready(function() { 

		function loadPage(){

			$.getJSON('roster.php', function(data) {
				var a = data.a;
				var b = data.b;
				var c = data.c;

			alert("a: "+a);// for testing
			alert("b: "+b);// for testing
			alert("c: "+c);// for testing


		loadPage(); // This will run on page load
		    loadPage() // this will run after every 5 seconds
		}, 8000);

	}); //ready(function

<div id="div-a"></div>
<div id="div-b"></div>
<div id="div-c"></div>

any idea?



Because you declare the variables inside the function, they only exist within the function.

I moved them out but the variables are still coming back blank:

function loadPage(){

	var a = "";
	var b = "";
	var c = "";

	$.getJSON('roster2.php', function(data) {
		a = data.a;
		b = data.b;
		c = data.c;

	alert("a: "+a);
	alert("b: "+b);
	alert("c: "+c);


If moving them outside of the inner function solved the “undefined” error, but they are empty, my guess is it’s because getJSON is asynchronous, i.e.

do this now
do this now
start doing this now, when done, do this
do this now
do this now

that is, the "do this now"s are happening before the “when done” happens.

Would moving the }); to after the jQuery('#div-c').html(c); solve the problem?

BTW, every 5 seconds might be a bit too short of a time for the browser to keep up with things.
Maybe try making it longer to give the getJSON more time to make it across the wires

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.