1

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> 
2
  • 1
    If you return JSON in php don't include html outside only JSON. Commented Apr 8, 2016 at 7:56
  • Is there another way to return the values? $row['answers'] just returns strings. Commented Apr 8, 2016 at 8:05

3 Answers 3

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);
             })

        }}
Sign up to request clarification or add additional context in comments.

15 Comments

Should be $result[] I'm guessing.
What does "remove html and add array collection." mean? How does it look like?
@flohdieter the contents of your DBCOMANSWERS.php should like like the code in this answer. See how the <html>.. part is removed and $result=[] meaning it's an array.
As mentioned by @madalinivascu put header('Content-Type: application/json'); before sending result back to clientside.
@ Sameer Jain How does the final return statement look like?
|
3

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);
                 })

            }}

6 Comments

Still nothing, is the "return"-statement: echo json_encode($result); ok?
The HTML tags still need to be removed.
@apokryfos Do you mean the HTML tags which gets returned to the ajax call?
@flohdieter in file DBCOMANSWERS.php only keep the stuff between the <?php ... ?> and delete the rest.
@apokryfos done it, now the given result is just the array with the key/value pairs.thank you. But i don't know how to append them to the paragraph. @madalin ivascu I tried the loop but got the following error message: Uncaught TypeError: Cannot use 'in' operator to search for 'length' in array(3) { [0]=> string(9) "Christian" [1]=> string(5) "Bj�rn" [2]=> string(6) "Steven" }
|
1

TRY:

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

Reference:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.