admin管理员组

文章数量:1323677

I want to return a json array back to the calling $.ajax function, but I only get the last item of the expected array. Maybe I don't produce an array?

If I click the button with the id "btn_getAnswers" the "$("#btn_getAnswers").click" gets fired and the code of "DBCOMANSWERS" will be executed. I want "$result" in "DBCOMANSWERS" to be an array filled with the values of my MYSQL-Database. I return "$result" formatted as JSON. The returned result should append to the paragraph with the id "output". So far, that works fine, but I except three strings to be returned and appended to the paragraph, now just a single one, the last catched entry from the database, gets appended.

I dont really can see where i have to put a loop for appending or whatever. Is the returned $result maybe not an array just the last entry of database because it gets overwritten?

Index.html:

<!DOCTYPE html>
<html>
    <head>
        <script src="jquery-1.12.3.js"></script> <!-- Import the jquery extension -->
        <script>
            $(document).ready(function () {
                $("#btn_getQuestion").click(function () {
                    $.ajax({
                        type: "POST",
                        url: "DBCOMQUESTIONS.php?q=" + $("#input").val(),
                        success: function (result) { //Performs an async AJAX request
                            if (result) {
                                $("#output").html(result); //assign the value of the result to the paragraph with the id "output"
                            }
                        }
                    });
                });

                $("#btn_getAnswers").click(function () {
                    $.ajax({
                        type: "POST",
                        url: "DBCOMANSWERS.php?q=" + $("#input").val(),
                        success: function (result) { //Performs an async AJAX request
                            if (result) {
                                $("#output").append(result);
                            }
                        }
                    });
                });
            });
        </script>
    </head>
    <body>
        <p id="output">This is a paragraph.</p>

        <input id="input"/>
        <button id="btn_getQuestion">Question</button>
        <button id="btn_getAnswers">Answers</button>

    </body>
</html>

DBCOMANSWERS.php:

<!DOCTYPE HTML>
<head>
</head>
<body>
    <?php
        include("connection.php");  //includes mysqli_connent with database
        include("ErrorHandler.php"); //includes error handling function
        set_error_handler("ErrorHandler"); //set the new error handler

        $q = intval($_GET['q']);

        $sql="SELECT * FROM tbl_answers WHERE QID ='".$q."'"; //define sql statement

        $query = mysqli_query($con,$sql); // get the data from the db

        while ($row = $query->fetch_array(MYSQLI_ASSOC)) { // fetches a result row as an associative array
            $result = $row['answer'];
        }

        echo json_encode($result); // return value of $result
        mysqli_close($con); // close connection with database
    ?>
</body>
<html> 

I want to return a json array back to the calling $.ajax function, but I only get the last item of the expected array. Maybe I don't produce an array?

If I click the button with the id "btn_getAnswers" the "$("#btn_getAnswers").click" gets fired and the code of "DBCOMANSWERS" will be executed. I want "$result" in "DBCOMANSWERS" to be an array filled with the values of my MYSQL-Database. I return "$result" formatted as JSON. The returned result should append to the paragraph with the id "output". So far, that works fine, but I except three strings to be returned and appended to the paragraph, now just a single one, the last catched entry from the database, gets appended.

I dont really can see where i have to put a loop for appending or whatever. Is the returned $result maybe not an array just the last entry of database because it gets overwritten?

Index.html:

<!DOCTYPE html>
<html>
    <head>
        <script src="jquery-1.12.3.js"></script> <!-- Import the jquery extension -->
        <script>
            $(document).ready(function () {
                $("#btn_getQuestion").click(function () {
                    $.ajax({
                        type: "POST",
                        url: "DBCOMQUESTIONS.php?q=" + $("#input").val(),
                        success: function (result) { //Performs an async AJAX request
                            if (result) {
                                $("#output").html(result); //assign the value of the result to the paragraph with the id "output"
                            }
                        }
                    });
                });

                $("#btn_getAnswers").click(function () {
                    $.ajax({
                        type: "POST",
                        url: "DBCOMANSWERS.php?q=" + $("#input").val(),
                        success: function (result) { //Performs an async AJAX request
                            if (result) {
                                $("#output").append(result);
                            }
                        }
                    });
                });
            });
        </script>
    </head>
    <body>
        <p id="output">This is a paragraph.</p>

        <input id="input"/>
        <button id="btn_getQuestion">Question</button>
        <button id="btn_getAnswers">Answers</button>

    </body>
</html>

DBCOMANSWERS.php:

<!DOCTYPE HTML>
<head>
</head>
<body>
    <?php
        include("connection.php");  //includes mysqli_connent with database
        include("ErrorHandler.php"); //includes error handling function
        set_error_handler("ErrorHandler"); //set the new error handler

        $q = intval($_GET['q']);

        $sql="SELECT * FROM tbl_answers WHERE QID ='".$q."'"; //define sql statement

        $query = mysqli_query($con,$sql); // get the data from the db

        while ($row = $query->fetch_array(MYSQLI_ASSOC)) { // fetches a result row as an associative array
            $result = $row['answer'];
        }

        echo json_encode($result); // return value of $result
        mysqli_close($con); // close connection with database
    ?>
</body>
<html> 
Share edited Apr 8, 2016 at 8:29 Dhaval Bharadva 3,0832 gold badges25 silver badges36 bronze badges asked Apr 8, 2016 at 7:54 flohdieterflohdieter 1304 silver badges15 bronze badges 2
  • 1 If you return JSON in php don't include html outside only JSON. – jcubic Commented Apr 8, 2016 at 7:56
  • Is there another way to return the values? $row['answers'] just returns strings. – flohdieter Commented Apr 8, 2016 at 8:05
Add a ment  | 

3 Answers 3

Reset to default 3

You need to do 2 thing

remove html and add array collection. This is how your DBCOMANSWERS.php must be look like

<?php
    include("connection.php");  //includes mysqli_connent with database
    include("ErrorHandler.php"); //includes error handling function
    set_error_handler("ErrorHandler"); //set the new error handler

    $q = intval($_GET['q']);

    $sql="SELECT * FROM tbl_answers WHERE QID ='".$q."'"; //define sql statement

    $query = mysqli_query($con,$sql); // get the data from the db
    $result = [];
    while ($row = $query->fetch_array(MYSQLI_ASSOC)) { // fetches a result row as an associative array
        $result [] = $row['answer'];
    }
    mysqli_close($con); // close connection with database
    header('Content-Type: application/json');
    echo json_encode($result); // return value of $result

?>

Then in your html as @madalinivascu suggests

success: function(result){ //Performs an async AJAX request
           result.forEach(function(i,v){
               $("#output").append(v.answer);
             })

        }}

try: remove all html tags and

include("ErrorHandler.php"); //includes error handling function
 set_error_handler("ErrorHandler"); //set the new error handler

from the ajaxed php file, create a array of results and append each result to it

    $result = []
     while ($row = $query->fetch_array(MYSQLI_ASSOC)) { // fetches a result row as an associative array
                $result[] = $row['answer'];
            }
header('Content-Type: application/json');//change header to json format

In your ajax function you need to do a loop:

success: function(result){ //Performs an async AJAX request
               result.forEach(function(i,v){
                   $("#output").append(v.answer);
                 })

            }}

TRY:

$result = []
 while ($row = $query->fetch_assoc()) { // fetches a result row as an associative array
            $result[] = $row['answer'];
}

Reference:

http://php/manual/en/mysqli-result.fetch-array.php

本文标签: javascriptHow to return array in php to ajax success functionStack Overflow