Search code examples
phpjsonjquery-post

Returning and parsing json array via php and jquery post


I'm trying to return a json array of names pulled from my database. I'm not sure what I'm missing here, but it never gets to the alert call. The returned data doesn't have to be json, I was just trying that approach first. It completes the INSERT call and I know that it is returning the correct data set. What's wrong with my code?

Javascript

function showDB() {
    $.post('example.php', $('#infoForm').serialize(), function(data) {  
        var json = $.parseJSON(data);
        $.each(json, function(i, item) {
            alert(item);
        });
    }, "json");
}

PHP

<?php
    $host = "www.host.com";
    $user = "user";
    $pwd = "password";
    $db = "exampleDB";

    $conn = mysqli_connect($host, $user, $pwd)or die("Error connecting to database.");
    mysqli_select_db($conn, $db) or die("Couldn't select the database."); 

    $name = $_POST['name'];
    $color = $_POST['color'];   
    $nameArray = array();

    $stmt = mysqli_stmt_init($conn);
    $query = "INSERT INTO people VALUES (?, ?)";
    mysqli_stmt_prepare($stmt, $query) or die("Failed to prepare statement.");
    mysqli_stmt_bind_param($stmt, "ss", $name, $color);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);

    $query = "SELECT name, COUNT(*) AS dupes FROM people GROUP BY name ORDER BY dupes DESC LIMIT 20";
    $result = mysqli_query($conn, $query);

    while ($row = $mysqli_fetch_array($result)) {
        array_push($nameArray, $row['name']);
    }

    echo json_encode($nameArray);

    mysqli_close($conn);

?>

Solution

  • There's a bug in your PHP code.

    Find this line of code:

    $nameArray[] = "";
    

    Replace to this line of code:

    $nameArray = array();
    

    Update

    Find this line of code:

    $query = "SELECT name, COUNT(*) AS dupes FROM people GROUP BY name ORDER BY dupes DESC LIMIT 20;";
    

    Replace to this line of code

    $query = "SELECT name, COUNT(*) AS dupes FROM people GROUP BY name ORDER BY dupes DESC LIMIT 20";
    

    Note the semicolon inside the string.


    Update Once Again

    Find this line of code:

    while ($row = $mysqli_fetch_array($result)) {
    

    Replace to this line of code

    while ($row = mysqli_fetch_array($result)) {
    

    mysqli_fetch_array is a function.