jquery ajax get database results using php json encode -
i have php code call using jquery ajax queries database , gets results , json encode results
//$rows query foreach($rows $row) { $sql = 'select field1, field2 table 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 this
[{"field1":"j1","field2":"0088","field3":"2928868"}][{"field1":"j2","field2":"0171","field3":"2928868"}][{"field1":"j2","field2":"0249","field3":"2928868"}]
the problem i'm getting processing in ajax response. s loop through each of array/rows , display data responsetext shows error.
i thought should don't know definite.
[{"field1":"j1","field2":"0088","field3":"2928868"},{"field1":"j2","field2":"0171","field3":"2928868"},{"field1":"j2","field2":"0249","field3":"2928868"}]
my question is, doing json_encode correctly , how output each of 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 focus order input $('#order').focus().val(''); }, error : function(xmlhttprequest, textstatus, errorthrown) { console.log('an ajax error thrown.'); console.log(xmlhttprequest); console.log(textstatus); console.log(errorthrown); } });
you should json encode entire output, instead of outputting json encoded version of each row:
$output = array(); //$rows query foreach($rows $row) { $sql = 'select field1, field2 table 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 question, work json in javascript, treat if array of objects. can use jquery loop through results $.each:
if(response.length != 0) { $.each(response, function(index, row) { console.log(row); // access row variables so: // row.field1, row.field2, row.field3, etc. } }
if prefer natively looping through, can following:
// let start @ zero. if response array length less i, execute block, increment 1. for(var = 0; response.length < i; += 1) { }
related question / further reading: how parse json in javascript
Comments
Post a Comment