Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have this php code that is call using jQuery ajax that queries a database and gets results and then json encode the results

//$rows is another query
foreach($rows as $row) {

    $sql = 'SELECT field1, field2 FROM table WHERE field1= :field';

    $stmt = $db->prepare($sql);
    $stmt->bindValue(':field', trim($row['field_1']));
    $stmt->execute();

    $array = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode($array);
}

The outputting json looks like this

[{"field1":"J1","field2":"0088","field3":"2928868"}][{"field1":"J2","field2":"0171","field3":"2928868"}][{"field1":"J2","field2":"0249","field3":"2928868"}]

The problem I'm getting is processing it in the Ajax response. What I would like to do i s loop through each of the array/rows and display the data but the responseText shows an error.

I thought it should look this but i don't know for definite.

[{"field1":"J1","field2":"0088","field3":"2928868"},{"field1":"J2","field2":"0171","field3":"2928868"},{"field1":"J2","field2":"0249","field3":"2928868"}]

My question is, am i doing the json_encode correctly and how do i output each of the rows?

$.ajax({
    type: "POST",
    url: "check.php",
    data: { order: order },
    dataType: "json",
    cache: false,
    success: function(response) {

        if(response.length != 0) {

            //output results here
        }
        else {
            $('#foo').text('Order number not found!!');
        }

        // set the focus to the order input
        $('#order').focus().val('');
    },
    error : function(XMLHttpRequest, textStatus, errorThrown) {
        console.log('An Ajax error was thrown.');
        console.log(XMLHttpRequest);
        console.log(textStatus);
        console.log(errorThrown);
    }
});
share|improve this question

1 Answer 1

up vote 3 down vote accepted

You should JSON encode the entire output, instead of outputting the json encoded version of each row:

$output = array();

//$rows is another query
foreach($rows as $row) {

    $sql = 'SELECT field1, field2 FROM table WHERE field1= :field';

    $stmt = $db->prepare($sql);
    $stmt->bindValue(':field', trim($row['field_1']));
    $stmt->execute();

    $array = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $output[] = $array;
}

echo json_encode($output);

Answering your question, to work with your JSON in JavaScript, you treat it as if it were an array of objects. You can even use jQuery to help loop through the results for you with $.each:

    if(response.length != 0) {

          $.each(response, function(index, row) {

              console.log(row);
              // Access your row variables like so:
              // row.field1, row.field2, row.field3, etc.
          }

    }

If you prefer natively looping through, you can do the following:

    // Let i start at zero. If the response array length is less than i, execute the block, then increment i by 1.
    for(var i = 0; response.length < i; i += 1) {

    }

Related Question / Further Reading: How to parse JSON in JavaScript

share|improve this answer
    
Thanks, works perfectly –  AdRock Jan 31 at 16:13

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.