0

I wrote a ajax call which gets an array returned from a .php file (when btn_getAnswers is clicked). Thats working fine so far with integer data (from database). But if I try to return the array filled with three Strings, no response get returned to the ajax call.

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").append(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(),
                        dataType:"json",
                        success: function(result){ //Performs an async AJAX request
                    if(result){
                        result.forEach(function(i,v){
                            $("#output").append("<br>" + i);
                        })
                    }
                }});
            });

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

<?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 = [];
$i = 0;

while ($row = $query->fetch_array(MYSQLI_NUM)){
    $result[$i] = $row[0];
    $i += 1;
}


mysqli_close($con); // close connection with database
header('Content-Type: application/json');
echo json_encode($result); // return value of $result
?>

If I assign $row[0](or $row[2],$row[3]) to $result[$i] everything works fine. But if I assign $row[1] to $result[$i], the returned "response" is empty, I look it up at "network" of the standard chrome browser development tool.

The only difference between $row[1] and $row[0] and the other columns ([2][3]) is, that the datatype of $row[1] is varchar and the others are int/tinyint.

Obviously the mistake has to be in the last few lines of the .php file. But I don't know what I've done wrong.

For your information: It's about the ajax called which gets triggered when the button with the id "btn_getAnswers" is clicked.

This is the error I am getting from json_encode

Malformed UTF-8 characters, possibly incorrectly encoded

6
  • 1
    At the end of your PHP script add echo json_last_error_msg(); and see if you're getting a JSON error Commented Apr 8, 2016 at 14:03
  • 1
    @jeroen, forEach is a native Array method Commented Apr 8, 2016 at 14:05
  • @jeroen there is one, as I said the code shown above works absolutely fine when im assigning $row[0],$row[2] or$row[3] to $result. @ Machavity I will give it a try. Commented Apr 8, 2016 at 14:06
  • @Machavity Thank you for this Hint! I've got an error message: "Malformed UTF-8 characters, possibly incorrectly encoded".What does this mean? @ jeroen, the forEach() works. Commented Apr 8, 2016 at 14:09
  • 1
    As was hinted at by Machavity, the character in the actual value returned by the database is invalid for json_encode. Use utf8_encode() (on each string) Commented Apr 8, 2016 at 14:10

2 Answers 2

2

So it looks like your database isn't storing UTF-8 characters. As such, you'll need to make sure you convert your characters to UTF-8 before running json_encode

$result = [];

while ($row = $query->fetch_array(MYSQLI_NUM)){
    $result[] = mb_convert_encoding($row[1], 'UTF-8');
}

That should convert your characters to UTF-8. Note that this works with all encodings, while utf8_encode() only works on one

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

Comments

1

I'll expand my comment into an actual answer, for anyone in the future to easily be able to see.

$row[1] must contain some characters or data that is/are non-UTF8.

So, use: $result[$i] = utf8_encode($row[0]);

And it will be parseable by json_encode. I've run into this problem many times myself!

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.