fmc
fmc

Reputation: 490

How to get PHP array results using JQuery

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.

Upvotes: 0

Views: 83

Answers (3)

Ruslan Osmanov
Ruslan Osmanov

Reputation: 21492

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

Upvotes: 2

Krzysztof Raciniewski
Krzysztof Raciniewski

Reputation: 4924

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>

Upvotes: 1

Adrian C.
Adrian C.

Reputation: 270

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

Upvotes: 1

Related Questions