0

I am attempting to access a JSON object from a PHP script that looks like:

$results = array(
    'total' => $all_totalf,
    'error' => $all_errorsf,
 );
echo json_encode($results);

The JSON object looks like:

{"total":"11,644","error":"179"}

Then I have a jQuery script that looks like:

var url = "get_control_data.php";
var total;
$.getJSON(url, function (data) {
var total = data.total;
});
document.getElementById("total").innerHTML = total;

I am stuck because total is being returned as "undefined". Does anyone know what I am doing wrong?

Thomas C
  • 55
  • 1
  • 5

1 Answers1

1

The problem is on this line in the getJSON callback:

var total = data.total;

The var here declares a new variable named total which is scoped only to the callback function. Remove the var and your code will set the total var in the outer scope instead.

That will only partly solve your problem. The other problem is that the outer code executes synchronously, whilst the callback code will execute asynchronously, sometime after the outer code has finished. This means that this line:

document.getElementById("total").innerHTML = total;

Is run before the total value has been read from the URL. Probably the easiest thing to do is just move that code into the callback, i.e.:

$.getJSON(url, function (data) {
  document.getElementById("total").innerHTML = data.total;
});
Julian Goacher
  • 545
  • 2
  • 6