1

I'm trying to get a JSON from a PHP page, but always I receive 'undefined'.

My jQuery code is:

<script>
    $(document).ready(function(){
        $("#lista_partecipanti").click(function(){
            $.post( "application/third_party/php_files/lista_partecipanti.php",
            { 
                user_id:<? echo $user_id; ?> , jam_id:<? echo $id_jam; ?>
            }, 
            function(data)
            {
                if(data) {
                    $("#div_lista_partecipanti").html('test' + data[0].username);
                }
                else
                {
                    alert("Error");                                     
                }
            });
        });
    });
</script>

My PHP code is:

<?php
include 'db_connect.php';

$a_id = $_POST['user_id'];
$b_id = $_POST['jam_id'];

$query = mysql_query("SELECT * FROM User a, Jam b WHERE a.id = b.owner AND a.id = $a_id AND b.id = $b_id");

if(mysql_num_rows() == 1) 
{
    $row = mysql_fetch_assoc($query);
    $data = array(
            'username' =>$row['username'],
            'user_id' => $row['id']
    );
    $data = json_encode($data);
    echo $data;    
}
else
    return false;

mysql_close();
?>

Solved

I solved my problem, it was not a PHP problem but the error was in the jquery code. I just added

data = $.parseJSON(data);

before

$("#div_lista_partecipanti").html(data.username);
Community
  • 1
  • 1
  • 1
    You have a SQL injection vulnerability. – SLaks Sep 18 '13 at 13:37
  • Show us the returned response. – SLaks Sep 18 '13 at 13:37
  • **Danger**: You are using [an **obsolete** database API](http://stackoverflow.com/q/12859942/19068) and should use a [modern replacement](http://php.net/manual/en/mysqlinfo.api.choosing.php). You are also **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that a modern API would make it easier to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from. – Quentin Sep 18 '13 at 13:39
  • The `while` loop is rather distracting - you've established there is only one row. – Quentin Sep 18 '13 at 13:39
  • Ok thanks! I fixed it. By the way, the javascript code is correct? –  Sep 18 '13 at 14:03

3 Answers3

2

Since you haven't specified otherwise, so PHP will claim that it is outputting an HTML document, and jQuery will treat the JSON as if it were HTML.

Add header("Content-Type: application/json"); before you output anything from your PHP.


Secondly, your JSON text consists of a single object, not an array of objects.

data[0].username should be just data.username

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

First you're very open to mysql injection, you should use mysqli or pdo prepared statements.

Second you shouldn't echo JSON inside the loop, it doesn't work like that, you need to add all your data to an array and then json_encode it and return it after the loop, although for your example it's only one item but still.

<?php
include 'db_connect.php';
header("Content-Type: application/json");

$a_id = $_POST['user_id'];
$b_id = $_POST['jam_id'];

$query = mysql_query("SELECT * FROM User a, Jam b WHERE a.id = b.owner AND a.id = $a_id AND b.id = $b_id");

if(mysql_num_rows() >= 1) {
    $data = array();
    while($row = mysql_fetch_assoc($query)){
        $data[] = array(
            'username' =>$row['username'],
            'user_id' => $row['id']
        );
    }
    echo json_encode($data);
} else {
    echo json_encode([]);
}
mysql_close();
OneOfOne
  • 95,033
  • 20
  • 184
  • 185
-1
        jQuery.ajax({
            type: "POST",
            url: "application/third_party/php_files/lista_partecipanti.php",
            data: "userid="+<?php echo $user_id; ?>+"&jam_id="<?php echo $id_jam; ?>,
            cache: false,
            success: function(response) {
                    ... 
                }
            }
        );
sskoko
  • 819
  • 6
  • 18