SACHIN GAJBHIYE SACHIN GAJBHIYE - 4 months ago 9
Ajax Question

I want to fetch array of database elements into table

I am trying to fetch array of my database into table by json object but it gives me my database first row as element of table and other as last database row .The middle rows are not shown in output. here is my code

<script id="source" language="javascript" type="text/javascript">

$(function ()
{
$.ajax({
url: 'example.php',
data: "",
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on recieve of reply

{
for(var i = 0; i < data.length; i++){
var uid = data[i];
var firstname = data[i];
var lastname = data[i];
var email = data[i];
var username = data[i];
var password = data[i];
}
$('#output').html("<b>uid: </b>"+uid+"<b> firstname: </b>"+firstname+"<b> lastname: </b>"+lastname+"<b> email: </b>"+email+"<b> username: </b>"+username+"<b> password: </b>"+password);


}
});
});
</script>


example.php

<?php

// server info
$server = 'localhost';
$user = 'root';
$pass = '';
$db = 'ocean';

$connection = mysql_connect($server, $user, $pass) or die(mysql_error());
$database = mysql_select_db($db) or die(mysql_error());


$result = mysql_query("select * from oops"); //query

$array = array();

while ($row = mysql_fetch_row($result)) {
$array[] = $row;
}

echo json_encode($array);



?>


output comes in that format
how should prepare that output in proper mannar

Answer

First:

$('#output').html("<some code>");

overwrites contents of #output everytime. So, you see only the last result. I think you should use either append():

$('#output').append("<some code>");

Or collect all rows into a variable and use html() once:

var html = "";
for(var i = 0; i < data.length; i++){
    var uid = data[i];             
    var firstname = data[i];       
    var lastname = data[i];
    var email = data[i];
    var username = data[i];
    var password = data[i];

    html += "<b>uid: </b>"+uid+"<b> firstname:   </b>"+firstname+"<b> lastname: </b>"+lastname+"<b> email: </b>"+email+"<b> username: </b>"+username+"<b> password: </b>"+password; 
}
$("#output").html( html );

Second:

var uid = data[i];             
var firstname = data[i];       
var lastname = data[i];

all this variables points to one value data[i]. Maybe it's:

var uid = data[i].uid;             
var firstname = data[i].firstname;       
var lastname = data[i].lastname;

?