0

Below are a couple of queries that ultimately build an array.

if(isset($_POST['getarray'])){
    try{
        $ret = array();
        $stmt = $db->prepare('SELECT groupdate, groupid
                                    FROM participationtemp
                                    WHERE memberid = :memberid
                                    AND groupid = :groupid
                                    ORDER BY groupdate, groupid DESC');
        $stmt->bindValue(':groupid', $_POST['groupid'], PDO::PARAM_INT);
        $stmt->bindValue(':memberid', $_SESSION['memberid'], PDO::PARAM_INT);
        $stmt->execute();
        $result = $stmt->fetchAll();
        foreach($result as $row){
            $attenddate = $row[0];
            $stmt = $db->prepare('SELECT h.clientid, attend, attend_date
                                        FROM history AS h 
                                        INNER JOIN suspended AS s on s.clientid = h.clientid                                    
                                        WHERE h.memberid = :memberid  
                                        AND h.groupid = :groupid
                                        AND attend_date = :attenddate
                                        AND suspend = "N"');
            $stmt->bindValue(':memberid', $_SESSION["memberid"], PDO::PARAM_INT);
            $stmt->bindValue(':groupid', $_POST['groupid'], PDO::PARAM_INT);
            $stmt->bindValue(':attenddate', $attenddate, PDO::PARAM_STR);
            $stmt->execute();
            $result = $stmt->fetchAll();
            foreach($result as $row ) {
                array_push($ret, ['id' => $row[0], 'gdate' => $row[2]]);
            }
        }
        echo json_encode($ret);
        exit();
    } catch (PDOException $ex){
            mail_error($ex);
    }
}

After returning to JQuery, alert(re); shows I successfully created the array.

success:function(re){
    alert(re);

enter image description here

But I'm having trouble accessing the array data. Without success, this is what i've tried:

data = $.parseJSON(re);

$.each(data, function(i, val) {
    alert(i + "=" + val);
});

and this:

data = $.parseJSON(re);

$.each(data, function(i, val) {
    if(i == "id"){
        alert(i + "=" + val);
    }
    if(i == "gdate"){
        alert(i + "=" + val);
    }
});

I've also tried dot notation.

$.each(re.id, function(i, val) {
    alert(i + "=" + val);
    }
});
$.each(re.gdate, function(i, val) {                             
    alert(i + "=" + val);                               
});

I've never used JSON before and don't understand why I can't retrieve the array data. Any help will be appreciated. Thanks.

5
  • 2
    Screenshots are evil. Please copy-paste all text outputs. Commented Oct 19, 2016 at 8:00
  • What did the alert contain with your first try? The JSON represents an array of objects, so I would expect you to see something like 0=[Object object]. Is this what happened or did the alert not even show? Commented Oct 19, 2016 at 8:03
  • I've also tried dot notation. - where is it? and please post the output of alert(i + "=" + val);. Commented Oct 19, 2016 at 8:04
  • can you initialize your json data with var re statically? let me know. Commented Oct 19, 2016 at 9:28
  • like var re = 'your json data'; and then ready for use data = $.parseJSON(re); Commented Oct 19, 2016 at 9:30

3 Answers 3

2

The following code checks whether re is a string, or an object. The latter is possible if jQuery.ajax() method is used with "json" dataType. Also, jQuery is capable of parsing JSON automatically, if the response MIME type is application/json (the Content-Type HTTP header), particularly. So it is a good idea to check if re has been parsed by jQuery.

var d = typeof re === 'string' ? JSON.parse(re)  : re;
var i;

for (i = 0; i < d.length; i++) {
  console.log("id = ", d[i].id,
              "gdate = ", d[i].gdate);
}

I'd recommend returning the appropriate content type from PHP:

    header ('Content-Type: application/json');
    echo json_encode($ret);
    exit();
Sign up to request clarification or add additional context in comments.

1 Comment

Adding the header did the trick. I appreciate your insight, Rusian. This has really helped me a lot. Thank you.
1
$.each(re, function(i, val) {
    alert(val.id + "=" + val.gdate);
});

1 Comment

This may also require dataType to be set to "json" in the $.ajax config.
1

Try this code :)

// Json in string format
var jsonString = '[{"id":"1", "gdate":"2016-10-13"},{"id":"2", "gdate":"2016-10-13"},{"id":"3", "gdate":"2016-10-13"},{"id":"4", "gdate":"2016-10-13"},{"id":"5", "gdate":"2016-10-13"},{"id":"6", "gdate":"2016-10-13"}]';

// Convert string to json object
var json = JSON.parse(jsonString);

// Iterate over json object
jQuery.each(json, function(index, value) {
  console.log(index, value);
});

// Simple access to attribute in json object
console.log('json[1][\'id\'] = ', json[1]['id']);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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.