JSON data in HTML page in a table - php

I struggling print all my data from DB to webpage using JSON.
But I not understand logical how it should work.
My JSON script:
<script>
$("document").ready(function() {
$.getJSON("test1.php", function(data) {
$("#div-my-table").text("<table>");
$.each(data, function(i, item) {
$("#div-my-table").append("<tr><td>" + item.code +"</td><td>" + item.name + "</td></tr>");
});
$("#div-my-table").append("</table>");
});
});
</script>
And test1.php file
<?php
require_once 'connection.php';
$sql = $conn -> prepare("SELECT * FROM DB_NAME");
$sql -> execute();
while ($row = $sql -> fetch(PDO::FETCH_ASSOC))
{
$values = array('code'=>$row['code'],
'line'=>$row['line']);
}
echo json_encode($values);
?>
and part of HTML:
<body>
<table id="div-my-table">
</table>
</body>
And system return back only:
<table>
undefined undefined
undefined undefined

First make below correction in your code
$values[] = array('code'=>$row['code'],'line'=>$row['line']);
Above change will append all database value to $value variable and will show all records instead of last record of db
Also Please check with your table name in below query
$sql = $conn -> prepare("SELECT * FROM DB_NAME");
It seems that you are taking db name constant here instead of table name as mentioned below.
$sql = $conn -> prepare("SELECT * FROM TABLE_NAME");

If you're expecting multiple rows, you need to gather the results properly. The $values gets overwritten every iteration.
while ($row = $sql->fetch(PDO::FETCH_ASSOC)) {
// add another dimension
$values[] = array(
'code'=>$row['code'],
'line'=>$row['line']
);
}
echo json_encode($values);
Or for just one line:
echo json_encode($sql->fetchAll(PDO::FETCH_ASSOC));
So that they are properly nested.
Then on your JS:
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("test1.php", function(data) {
var table_rows = '';
$.each(data, function(i, item) {
table_rows += "<tr><td>" + item.code +"</td><td>" + item.name + "</td></tr>");
});
$("#div-my-table").html(table_rows);
});
});
</script>

You're overwriting the same $values variable each time through the loop. At the end, it will just contain a single row, not an array of all the rows. You need to add each row to $values, not replace it. It should be:
$values = array();
while ($row = $sql -> fetch(PDO::FETCH_ASSOC))
{
$values[] = $row;
}
echo json_encode($values);
Also, your jQuery is wrong. You shouldn't use .text() when you're creating HTML, you should use .html(). And you don't need to append </table> -- these functions operate on the DOM, not the HTML, and the DOM always has complete elements.
$("document").ready(function() {
$.getJSON("test1.php", function(data) {
var table = $("<table>");
$("#div-my-table").empty().append(table);
$.each(data, function(i, item) {
table.append("<tr><td>" + item.code +"</td><td>" + item.name + "</td></tr>");
});
});
});

Use last.after();
Instead of append();

Related

json_encode for more than 2 arrays

I have 2 tables to be retrieved from database with 2 different queries and needs to be encoded in json and send to ajax.The issue is I am not able to pass 2 json's to ajax .
I have tried with echo json_encode(array($data1,$data2)); but it is not working.
//My php code
$query = $db->query("select * from table1 where valu1='".$value1."'");
while ($row = $query->fetch_assoc()) {
$data1['value1'] = $row['value1'];
$data1['value2'] = $row['value2'];
}
$query = $db->query("select * from table2 where value2='".$value2."' ");
while ($row = $query->fetch_assoc()) {
$data2['value2'] = $row['value2'];
$data2['value3'] = $row['value3'];
}
echo json_encode(array($data1,$data2));
//My AJAX code
$(document).ready(function(){
$('#Form').submit(function(e){
e.preventDefault(); // stops the form submission
$.ajax({
url:$(this).attr('action'), // action attribute of form to send the values
type:$(this).attr('method'), // method used in the form
data:$(this).serialize(), // data to be sent to php
dataType:"json",
success:function(data){
//main
alert(data.value1);
},
error:function(err){
alert(err);
}
});
});
});
Kindly help in solving this issue.Thanks in advance
In PHP:
echo json_encode(array($data1, $data2));
In AJAX:
var data1 = data[0];
var data2 = data[1];
$.each(data1, function() {
console.log(this.value1 + ',' + this.value2);
});
$.each(data2, function() {
console.log(this.value2 + ',' + this.value3);
});
EDIT:
After a whole year, I just noticed that the initial PHP code was wrong, because the loop for the sql result would overwrite each time the values of the array. So, the correct one is this:
$query = $db->query("select * from table1 where valu1='".$value1."'");
while ($row = $query->fetch_assoc()) {
$data1[] = array('value1' => $row['value1'], 'value2' => $row['value2']);
}
$query = $db->query("select * from table2 where value2='".$value2."' ");
while ($row = $query->fetch_assoc()) {
$data2[] = array('value2' => $row['value2'], 'value3' => $row['value3']);
}
echo json_encode(array($data1,$data2));
Your code is fine, you just have to handle the two arrays within your success function:
success: function(data){
var object1 = data[0];
var object2 = data[1];
// Do whatever you like to do with them
}

load json data from database into slideToggle

I'm trying to load applicants info that i get from database (fisrt name, lasta name, ID number) in a slidetoggle that appears after clicking "Display applicants" button.
My code keeps showing ERROR DETECTED message, after I click the button "display applicants" an slidetoggle should appear and the json data be shown on the slide. can someone give me some directions about what i'm doing wrong here.
Query:
if(isset($_GET['id'])){
$id_oferta = $_GET['id'];
$sql ="SELECT postulacion.* FROM postulacion WHERE id_oferta = '". $id_oferta ."'";
$listapostulantes = mysql_query($sql) or die(mysql_error());
$return_arr= array();
$num = mysql_num_rows($listapostulantes);
if($num > 0){
while($row = mysql_fetch_array($listapostulantes, MYSQL_ASSOC)){
$return_arr[] = $row;
}
echo json_encode($return_arr);
}
}
Script:
$(document).ready(function(){
$('.myslide').hide();
$(".postulantes").on('click', function(e){
e.preventDefault();
if($(this).parent().next().css('display') == 'none'){
$('.myslide').hide('fast');
$(this).parent().next().slideToggle('slow');
var link = $(this).attr('href').split('&');
var idd= link[1].match(/id=([0-9]+)/)[1];
$.ajax({
url: link[0],
type: 'GET',
dataType:'json',
data:{'id': idd},
success:function(data){
// console.log();
var htmlStr = '';
$.each(data, function(key, value){
htmlStr += '<p>' + value.rut_usuario + '</p>';
});
$(".myslide").html(htmlStr);
},
error: function(){
$("#listaofertas").html("ERROR DETECTED");
//console.log();
}
});
}
});
});
json
Your response, as shown under the Respuesta tab, includes not only JSON, but some HTML as well. Get rid of the html, and make sure only JSON is returned, and then jquery should execute your success callback
Use this to split the response and "cut out" the html part.
$splitted = explode("<!DOCTYPE HTML>",json_encode($return_arr));
echo $splitted[0];

jquerymobile selectmenu not populating

I am trying to populate a selected menu when the page is created but there are no options that show.
$(document).ready(function() {
$.ajax('patientlist.php', function(data){
var html = '';
var len = data.length;
for (var i = 0; i< len; i++) {
html += '<option value="' + data[i].patient_id + '">' + data[i].patient_firstname + data[i].patient_lastname + '</option>';}
$('#patientselect').append(html);
});
});
my patientlist.php
$result = mysql_query("SELECT `patient_id`, `patient_firstname`, `patient_lastname` FROM `patients` WHERE `company_id` = " . $user_data['company_id'] . " ORDER BY `patient_firstname`");
while($row = mysql_fetch_assoc($result)) {
$data[] = $row;
echo json_encode( $data );
}
My result from the php page
[{"patient_id":"9","patient_firstname":"Adam","patient_lastname":"Steve"}] etc...
Really appreciate any help, been stuck on this for a week!
So, posting again.
First of all, you should put the echo json_encode( $data ); out of your while loop
while($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
echo json_encode( $data );
Second, your $ajax syntax isn't correct, change this to $.post and tell the $.post request you are expecting a 'json' response from patientlist.php
$(document).ready(function() {
$.post('patientlist.php', {}, function(data){
/* code */
}, 'json'); // <= set data type json here
});
When retrieving a valid json string, you can iterate over data by using the $.each method
$.each(data, function(index, patient) {
console.log(patient.patient_id); // or use patient['patient_id']
});
At least you will now receive a valid request.
Noticing your HTML, do not use .append if it is not a DOM element, you are just building html elements as a string, so use instead
$('#patientselect').html(html);

What am I doing wrong in the code?I am making a jquery/json call to call the data from the database

I have pasted the code for index.php and jsonPhp.php.I am new to JSON and learning json with ajax.Here,I am trying to get the data from the server using json.When I click on the link SERVER DATA, The data from the server must appear without re-loading the page using jQuery/json.I have written the code but I dont get it working.Please help.
Thanks.
<head>
<title>JSON WITH PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"
type="text/javascript"></script>
<script type="text/javascript">
< ![CDATA[
$(function () {
$('#click').click(function () {
$.post('jsonPhp.php', function (data) {
//$("#content").html(data)+'<br>';
var pushedData = jQuery.parseJSON(data);
var htmlData = "";
//loop through using jQuery
$.each(pushedData, function (i, field) {
htmlData = htmlData + '-' + field.id + ',' + field.place + ',' + field.description + '<br>';
});
$('#content').html(htmlData);
});
});
});]] >
</script>
</head>
<body>Click on the link below to get the data from the Server Dynamicallly!
<br
/>
Server Data
<div id="content"></div>
</body>
<?php
$db = mysql_connect("localhost","root","")or die(mysql_error());
mysql_select_db("places",$db) or die(mysql_error());
if(isset($_POST['place']))
$place=$_POST['place'];
if(isset($_POST['description']))
$description=$_POST['description'];
$myrows = array();
$result = mysql_query("SELECT * FROM search");
while( $row = mysql_fetch_assoc($result) ) {
$myrows[] = $row;
}
echo json_encode($myrows);
?>
Try specifying parameters, that you send with POST request, resulting something like this:
$.post('jsonPhp.php', { place:'myplace', /* other params */ }, function (data) { ...
Your jQuery post doesn't post the necessary items.
Be careful using this code.

getJSON + json_encode + query php

Okay i change the script like this ! why it dont work ?!?
demo.php
while($row = mysql_fetch_array($result)){
$array[] = array(
'var1' => $row['var1'],
'var2' => $row['var2'],
'var3' => $row['var3'],
'var4' => $row['var4'],
);
}
print json_encode($array);
demo.js
$.getJSON("demo.php",function(result){
$.each(result, function(i, obj){
$(obj.var1).appendTo('div id="var1"');
$(obj.var2).appendTo('div id="var2"');
$(obj.var3).appendTo('div id="var3"');
$(obj.var4).appendTo('div id="var4"');
});
Firstly, the PHP:
As previously mentioned, you don't need quotes (") around the variables in your database connection, it's pointless.
You also need to get all the rows before JSON encoding.
Change:
echo json_encode(mysql_fetch_assoc($result));
To
$return = array();
while ($row = mysql_fetch_assoc($result))
{
$return[] = $row;
}
echo json_encode($return);
So that all the rows from the database are returned, instead of just the first.
Next for your jQuery:
Try changing: $('div').html(obj.attribute1+" "+obj.attribute2 ecc...);
To: $(obj.attribute1+" "+obj.attribute2 ecc...).appendTo('div');
Or: $('<div>' + obj.attribute1+" "+obj.attribute2 ecc... + '</div>').appendTo('body'); if you want each object in it's own container.
The way you are currently doing it will just overwrite the HTML for every div on the page for each iteration so that div elements will eventually only contain details for the last object in the collection.
Edit:
$.getJSON("demo.php",function(result){
var $id = 0;
$.each(result, function(i, obj){
$id ++;
$('<div id="obj' + $id + '"/>').appendTo('body');
$('<span class="var1">' + obj.var1 + '</span>').appendTo('div#obj' + $id);
$('<span class="var2">' + obj.var2 + '</span>').appendTo('div#obj' + $id);
$('<span class="var3">' + obj.var3 + '</span>').appendTo('div#obj' + $id);
$('<span class="var4">' + obj.var4 + '</span>').appendTo('div#obj' + $id);
});
});
Edit 2:
If you are trying to get each of the 'varX' from all elements into a single div, then just define the four divs (<div id="var1"/>, <div id="var2"/>, ...), and use this code:
$.getJSON("demo.php",function(result){
$.each(result, function(i, obj){
$(obj.var1).appendTo('div#var1');
$(obj.var2).appendTo('div#var2');
$(obj.var3).appendTo('div#var3');
$(obj.var4).appendTo('div#var4');
});
});

Categories