Jason Chen
Jason Chen

Reputation: 2577

ajax get json data from mysqli

My Ajax looks like this:

    $.ajax({
      method: "GET",
      url: 'yooarel.php?',
      data: servicedata,
      dataType: "JSON",
      success: function(data){
        $("#count_math").html(data[0].cnt);
      }       
    });
  }

Inside yooarel.php? I have the following PHP echo code.

$theclass = "SELECT _latin1 'math' as class";

$theschool = "
  SELECT s.class,
  COUNT(m.class) AS cnt
  FROM ( {$theclass} ) s
  LEFT
  JOIN members m
  ON m.class = s.class
";
$theclose = "GROUP BY s.class";

$result = $con->query("
    {$theschool}{$theclass}
");

$rows = $result->fetch_assoc();
echo json_encode($rows);
mysqli_close($con);

$con represents the mysql connection. The query is broken up to have room for conditional events. The scenario here is that I want to retrieve a tally of students from different classes and output their count.

Currently the code I have does not work, as it tells me that cnt is undefined.

If I remove dataType:"JSON" and remove ([0].cnt) then I can verify that my values show up in the #count_math div as a json list.

I am currently tying to resolve this using fetch_assoc() instead of fetch_all() because for some reason, fetch_all() only works in my local environment, and not my Hostgator server. I have tried updating the PHP version and that did not work.

Let me know if there is any info that should have been on here.

Upvotes: 0

Views: 569

Answers (1)

Barmar
Barmar

Reputation: 780974

fetch_assoc() just returns one row. If you want all rows, you need to call it in a loop.

$rows = array();
while ($row = $result->fetch_assoc()) {
    $rows[] = $row;
}
echo json_encode($rows);

fetch_all() only works if you have the MYSQLND driver, I suspect your Hostgator server doesn't have this.

Upvotes: 1

Related Questions