简体   繁体   中英

access the response Json data in javascript

I'm using a Json in my HTML to get data from Database but I can't access the data of returned Json here is my HTML function :

$.ajax({
    type: "POST",
    url: 'fetch.php',
    dataType: 'json',
    data: {func:"viewCert",tracking_code:tracking_code},
    success: function (data) {
        if (data!=null) {
            document.getElementById("generation_date").textContent = data.certInfo.timestamp;
        } else {
            alert("Something's Wrong! Try Later");
            window.location = "../views/failed.html";
        }
    }
});

and here is fetch.php function :

function viewCert($tracking_code) {
    $connect = connection();
     $connect->set_charset("utf8");
    $sql = "SELECT timestamp FROM certificate WHERE tracking_code=?";
    $result = $connect->prepare($sql);
    $result->bind_param("s",$tracking_code);
    $result->execute();
    $res=$result->get_result();
    while ($row=$res->fetch_object()) {
        $output[]=$row;
    }
    echo json_encode(array('certInfo' => $output));
}

Sorry for this question I'm just new in HTML and Javascript , so anyone know why timestamp won't be set in 'generation_date' element? any help will be much appreciated

In your PHP, $output seems to be an array. So in your javascript you need to access on the good index to get the data.

Try :

 document.getElementById("generation_date").textContent = data.certInfo[0].timestamp;
 ----------------------------------------------------------------------^^^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM