J. Doe
J. Doe

Reputation: 483

cannot receive json in js ajax request from php file

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

Upvotes: 0

Views: 121

Answers (1)

Lelio Faieta
Lelio Faieta

Reputation: 6684

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.

Upvotes: 1

Related Questions