0

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?

mateusbrigido
  • 37
  • 1
  • 8

2 Answers2

1

What am I doing wrong?

You are expecting getJSON to be synchronous, when in fact it's asynchronous. You must use a callback instead of trying to assign the return of getJSON to total:

$.getJSON('totalDeImoveis.php?id=316', function(data){
    console.log(data);
    // continue program flow from here
});

You can find a more detailed explanation on the accepted answer to How do I return the response from an asynchronous call?.

Community
  • 1
  • 1
bfavaretto
  • 71,580
  • 16
  • 111
  • 150
1

RTM: http://api.jquery.com/jQuery.getJSON/

.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.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Marc B
  • 356,200
  • 43
  • 426
  • 500