How to define a variable js with the result of a php code using json?


This question already has an answer here:

  • How do I return the response from an asynchronous call? 22 answers

I'm tryint to set a js variable with the result of a php code using json, but it isn't working. The code below shows what i'm trying to do.

The PHP is returning this.

echo json_encode($row['total']);

I'm trying to recover the variable in js, this is the code.

var total = $.getJSON('totalDeImoveis.php?id=316');

What am I doing wrong?


.getJSON doesn't return the "getted" value. You need to define a function to accept the result once the server spits it out, e.g.

var total;

$.getJSON('totalDeImoveis.php?id=316', function(returned_data) {
    total = returned_data;

Also remember that AJAX calls (which is what getJSON) is doing is an asynchronous call. The .getJSON call will return IMMEDIATELY and your code will continue executing. the result of the AJAX call won't be available until sometime later, when the server actually finishes processing and sends back the result. You'll probably want to "pause" your code and have the .getJSON success handler resume processing once the answer is available.