0

I'm trying to get data from my database using ajax and php, but whenever I try to get it I get an error with ajax. Here is my code:

HTML

Here is my code where I request the php file.

<body>
    <div id="wrapper">
        <h2>Coffe Shop</h2>
        <p class="bold">Drink orders:</p>

        <ul class="orders">
        </ul>

        <p class="bold">Add an order:</p>
        <p>Drink: <input type="text" id="name"/><input type="submit" id="submit"/></p>

        <button id="refresh">CLICK ME</button>
    </div>

    <script>
        $(function (){
            $("#refresh").on("click", function() {
               $.ajax({
                type: "GET",
                url: "data.php",
                dataType: "json",
                success: function(names){
                    $.each(names, function(name){
                        alert(name);
                    });
                },
                error: function(){
                    alert("error");
                }
           });
        }); 
            });

    </script>
</body>

PHP

Here is my PHP file

<?php

$conn = mysqli_connect("localhost:8080", "root", "", "test1")
    or die("Error with connection");


$sql = "SELECT ime FROM users;";

$result = mysqli_query($conn, $sql);

$row = mysqli_fetch_array($result);
$names = array();

while($row){
    $name = array(
        "name"=> $row['ime']
    );

$names[] = $name;
}

echo json_encode($names);
1
  • 3
    What is the error? Commented May 25, 2017 at 13:46

1 Answer 1

2

You have an infinite loop in your PHP. You're just fetching one row, and then looping over that same row. Since you never change $row in the loop, it never ends. It should be:

while ($row = mysqli_fetch_assoc($result)) {
    $name = array('name' => $row['ime']);
    $names[] = $name;
}

Once you fix that, the JSON you'll be sending will look like:

[{"name": "Some name"}, {"name": "Another name"}, {"name": "Fred"}]

In your Javascript, you're not accessing the name property. Change

alert(name);

to:

alert(name.name);

Or you could change the PHP so it just sends an array of strings instead of objects:

while ($row = mysqli_fetch_assoc($result)) {
    $names[] = $row['ime'];
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.