user2634873
user2634873

Reputation: 49

Display JSON data in a PHP page

I have a PHP page that will return JSON data as output. I get the data as AJAX. I want to display the results from JSON. But when I try to display each value I am getting undefined error.

This is the PHP code for getting data:

if (isset($_POST['dcqid'])) {
        $question_id = intval($_POST['dcqid']);


        if ($question_id != "") {
            $user_id = $session->id;
            $questiondetail = getData("dcquestions", "dcqid", "dcqid", $question_id, "", "");
            //print_r($questiondetail);
            echo json_encode($questiondetail);
            ?>
        }
    }

This is the JSON output I am getting

[{"dcqid":"10","current_id":"3","question":"Another Question","answer":"This is another question","description":"This is the description","date":"2017-08-10 11:55:51","active":"1"}]

This is the AJAX code I am using to display data

<script type="text/javascript">
    $(".edit-current").on('click', function (e) {
        e.preventDefault();
        var id = $(this).data('currentid');
        alert(id);
        var url = "<?php SITE_URL ?>admin/" + "admin_edit_current.php";
        var info = 'dcqid=' + id;

        $.ajax({
            type: "POST",
            url: url,
            data: info,
            success: function (data) {
                console.log(data);
                console.log(data.dcqid); // undefined 

            },
            error: function (data) {
                alert(data.responseText);
                alert("Error occured in showing details");
            }
        })

    });
</script>

I am currently getting undefined for the values I want to display.

Upvotes: 0

Views: 46

Answers (2)

shunz19
shunz19

Reputation: 534

Its because the data var is an array. it's like this:

data = [
    {
        dcqid : 123
    }
]

so try using

console.log(data[0].dcqid)

Upvotes: 2

JYoThI
JYoThI

Reputation: 12085

1st : Access it like this

console.log(data[0].dcqid); 

2nd : Add dataType in ajax

 dataType:"json"

Note : your value is inside the 0th index . so you need to access it like above.

var data =[{"dcqid":"10","current_id":"3","question":"Another Question","answer":"This is another question","description":"This is the description","date":"2017-08-10 11:55:51","active":"1"}];

console.log(data[0].dcqid);

Upvotes: 0

Related Questions