0

onclick onto a button the js starts an ajax request to the php file. The php file then gets all entries of one table of a database with php-loop. adding them to an array then the php file parse it to a JSON and echos it back to the ajax request. on success the ajax request should output an alert but neither do i get an error nor a alert.

After adding some changes according to the comments. it is now showing the error message 2 error messages randomly:

Fehler: {"readyState":0,"responseText":"","status":0,"statusText":"error"}


Fehler: {"readyState":4,"responseText":"<br />\n<b>Fatal error</b>:  Uncaught Error: Cannot use object of type mysqli_result as array in C:\\xampp\\htdocs\\integration\\get.php:32\nStack trace:\n#0 C:\\xampp\\htdocs\\integration\\get.php(13): getLevel1()\n#1 {main}\n  thrown in <b>C:\\xampp\\htdocs\\integration\\get.php</b> on line <b>32</b><br />\n","status":200,"statusText":"OK"}

php request (mysqli attributes are left out on purpose):

    $func = $_POST['func'];

if ($func == "getLevel1"){
    getLevel1();
}

$result = array();

function getLevel1(){
    // Create connection
    $conn = new mysqli(servername, username, password, dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $sql = "SELECT id, name FROM capability_level1";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
            $result[] = '<button onclick="capability('. $row["id"] .')">' . $row["name"]. '</button></br>';
        }
        echo json_encode($result);
    } else {
        echo json_encode("0 results");
    }
    $conn->close();
}

js ajax call:

async function getLevel1() {
    return $.ajax({
        type: "POST",
        dataType: "json",
        url: "get.php",
        data: {
            func: "getLevel1"
        },
        success: function(data) {
        alert(JSON.stringify(data));
        console.log(data);
        },
        error: function(data) {
        alert("Fehler: "+ JSON.stringify(data));
        }
    });
}
2
  • 1
    json_encode must be after the while loop, not inside Commented Jun 7, 2018 at 8:59
  • And if you use dataType: "json" JQuery will do the JSON.parse() for you and you can remove the JSON.parse() from your js Commented Jun 7, 2018 at 9:07

1 Answer 1

1

You need to put the json encoding when you have a complete array to be encoded: after the while:

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $result[] = '<button onclick="capability('. $row["id"] .')">' . $row["name"]. '</button></br>';

    }
    echo json_encode($result);
} else {

Also note that you probably have to change your data type to Json (and send a json to php) to be able to return it. Actually your Ajax is waiting for text to be returned (based on the data type)

For your further error: it is related to the point that you are fetching the rows from mysql using the wrong function. See this question for more details on how to fix it.

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

3 Comments

what a stupid thinking mistake :S but it is still not alerting anything :S
thank you, did the changes, now it returns the error message from the ajax call -.-
see my update. The error is returned because you are using the wrong function to retrieve the results that then you will encode. The accepted answer is what you are looking for

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.