0

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.

2 Answers 2

2

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

data = [
    {
        dcqid : 123
    }
]

so try using

console.log(data[0].dcqid)
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

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.