John
John

Reputation: 1629

AJAX does not recognize json array

Ajax does not want to recognize my $google['cities'] when called as data.cities.

The output is: 12 undefined undefined.

It works well (output are database records) if i remove $google['number']=12, and define database array just as $google[]=$row.

Any ideas?

PHP:

<?php

$con = mysql_connect("localhost","root","");

if(!$con) {

    die("Connection Error: ".mysql_error());

}

mysql_select_db("avtost", $con);

$pasteta = $_POST["white"];

$places = mysql_query("SELECT sDo FROM bstop WHERE sOd='$pasteta'");

mysql_close($con);

$google=array();

while ($row=mysql_fetch_array($places)) {
    $google["cities"]=$row;
}

$google['number']=12;

if (mysql_num_rows($places)>0) {

    echo json_encode($google);
} else { echo 'Ni rezultatov';}



?>

JQuery:

<script type="text/javascript">

$(document).ready(function(){

  $('#submit').click(function(){

    var white = $('#white').val();

    $.ajax({

    type:"POST",
    url:"page.php",
    dataType:'json',
    data:{white:white},
    success: function(data){

        var result='';
        $.each(data.cities, function(i,e) {
        result += '<div>'+e.sDo+'</div>';
        });
        $("#res").append(data.number);
        $("#res").append(result);

    }


    });


  });  

});

</script>

Upvotes: 0

Views: 279

Answers (3)

Kurt
Kurt

Reputation: 7212

Some tips:

1) you should be using prepared statements to secure your code (mysqli prepared). This will give you something like:

// connect to database and check it
// ...
$stmt = $mysqli->prepare('SELECT sDo FROM bstop WHERE sOd=?');
$stmt->bind_param('s',$pasteta);
$stmt->bind_result($sDo);
$stmt->execute();
while($stmt->fetch())
    $google['cities'][] = $sDo;
$google['number'] = 12;
$stmt->close();
$mysqli->close();
// ...

2) Improve your variable, table and column names. They are a bit confusing.

3) Instead of returning 'Ni rezultatov', you should return JSON. Such as, {"status":"FAILED"}, subsequently returning {"status":"OK", ... } for successful requests.

Upvotes: 3

John
John

Reputation: 1629

I solved it myself:

PHP:

while($row=mysql_fetch_array($places)){

$google['cities'][]=$row;

}

$google['number']=12;

echo json_encode($google);

Upvotes: 1

KDaker
KDaker

Reputation: 5909

you are overwriting the cities key in $google every time you loop for a row in $places. you can use:

while ($row=mysql_fetch_array($places)) {
    $google[]=$row;
}

$google[]=12;

and then simply grab the last value value of the array if you want to get the number key, or just pass the number as a separate variable $number.

Upvotes: 3

Related Questions