Parsing JSON Data From MySQL Table to Different Divs
Having a jQuery Ajax request from MySQL database I know how to render the data in an HTML element format like tables or list as below:
- $.ajax({
- type:"POST",
- url:"appdata.php",
- success: function (newdata) {
- $('#result').html(newdata);
- }
- });
The PHP as:
- $mysqli = new mysqli('localhost', 'root', '******', '********');
- $resultStr = '';
- $query = 'SELECT * FROM appusers';
- if ($result = $mysqli->query($query)) {
- if ($result->num_rows > 0) {
- $resultStr.='<ul>';
- while($row = $result->fetch_assoc()){
- $resultStr.= '<li>'.$row['fname'].' - '.$row['lname'].' - '.$row['phone'].'</li>';
- }
- $resultStr.= '</ul>';
- }
- else {
- $resultStr = 'Nothing Found';
- }
- }
- echo $resultStr;
- ?>
The other option, also, is passing the result as JSON by using the json_encode() as below
- $mysqli = new mysqli('localhost', 'root', '******', '********');
- $query = 'SELECT * FROM appusers';
- $result = $mysqli->query($query)->fetch_array();
- echo json_encode($result);
Now I am totally confused how to use this json_encode($result) in the Ajax call? For example can you please let me know if I want render the result of the query in series of divs like
- <div id"fname"></div>
- <div id"lname"></div>
- <div id"phone"></div>
how can I parse this in ajax success property? and associuate each field on related div? Thanks for you help in advanced.