1

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

5
  • 2
    Use console.log(data) after success: function (data) { and show us the result ? Also show generation_date element. Commented Feb 20, 2019 at 10:27
  • 2
    I think $output is an array, maybe you need to access with an index to the desired value ? like data.certInfo[0].timestamp Commented Feb 20, 2019 at 10:28
  • 1
    have you tried doing. $.parseJSON(data) ? Commented Feb 20, 2019 at 10:30
  • @MorganFreeFarm sorry where the Log prints? in inspect part of browser? Commented Feb 20, 2019 at 10:37
  • 1
    @ShakibKarami press f12 to show the console Commented Feb 20, 2019 at 10:38

1 Answer 1

1

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;
 ----------------------------------------------------------------------^^^
Sign up to request clarification or add additional context in comments.

2 Comments

@ShakibKarami Like MorganFreeFarm comment, we need the content of consol.log(data) at the start of the success function to help you
sorry I was wrong certInfo was an array :) thanks a lot for your help

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.