0

I'm trying to use a JSON array generated in a php function in a javascript function. My code is this:

$query = "SELECT lat, lng FROM Eventi";
$result = mysql_query($query) or die(mysql_error() . "<br/><br/>" . $query);
if (mysql_affected_rows() != 0) {
     while($r = mysql_fetch_array($result)) {
        $rows =  array(
           "latitudine" => $r['lat'],
           "longitudine" => $r['lng'],
       );}
       $risultato_rows = json_encode($rows);

Now I want to recover them in a subroutine did javascript to use them, and I tried so:

var res = JSON.parse($risultato_rows);
    alert var prova = res.[latitudine];

This code doesn't work; what can I do to make it function properly?

2
  • Is the first snippet PHP and the second snippet JavaScript? If so, you can't use the same variables directly. Commented Nov 13, 2012 at 18:35
  • are you echo? var res = JSON.parse(<?php echo $risultato_rows?>); console log after its, console.log(res); Commented Nov 13, 2012 at 18:37

3 Answers 3

2
res.[latitudine];  // You seem to mix up both the
                   // dot and bracket notation..

supposed to be either

res.latitudine; OR res["latitudine"];

Sign up to request clarification or add additional context in comments.

Comments

1

A PHP variable isn't directly visible in Javascript. Supposing you're not doing AJAX but just trying to embedd JSON in your script, you might do this :

?><script>
var res = JSON.parse('<?php echo $risultato_rows; ?>');
var prova = res.latitudine;
alert (prova);
</script><?php

3 Comments

One may just echo the JSON directly since JSON is a subset of JavaScript.
@Asad The keys are always quoted, how does that prevent you from just echoing it.
I try with: var res = JSON.parse('<?php echo $risultato_rows; ?>'); var prova = res.latitudine; alert (prova); and var res = JSON.parse('<?= $risultato_rows; ?>'); var prova = res.latitudine; alert (prova); but in both case don't work!
0

There are a few problems with your code:

  1. You need to echo the JSON string that is contained in $risultato_rows. That is:

    var res = JSON.parse('<?= $risultato_rows; ?>');

  2. When accessing properties, you put the key name as a string in the brackets. To access the latitudine property, you would use res.["latitudine"]

  3. The var keyword is used when declaring variables, not when accessing them. Use separate statements to assign the value to prova and alert it.

1 Comment

I try with: var res = JSON.parse('<?php echo $risultato_rows; ?>'); var prova = res.latitudine; alert (prova); and var res = JSON.parse('<?= $risultato_rows; ?>'); var prova = res.latitudine; alert (prova); but in both case don't work!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.