Json reading data from json call in to a table - php

I have a script that reads the content of a Json string and creates a table to display the data. This works fine as long as I include the Json string in the JQuery function. What I need to do is call another php file which returns the Json string.
I have written the script that returns the Json string:
[{"ClientName":"Name","RoomName":"Room 2","RoomFromTime":"06:00:00","RoomToTime":"17:00:00"},{"ClientName":"Name","RoomName":"Room 6","RoomFromTime":"06:00:00","RoomToTime":"23:00:00"},{"ClientName":"Name","RoomName":"Room 1","RoomFromTime":"07:00:00","RoomToTime":"17:00:00"},{"ClientName":"Name","RoomName":"Room 14","RoomFromTime":"07:00:00","RoomToTime":"23:00:00"},{"ClientName":"Name","RoomName":"Room 12","RoomFromTime":"07:00:00","RoomToTime":"19:00:00"},{"ClientName":"Name","RoomName":"Room 10","RoomFromTime":"07:00:00","RoomToTime":"23:00:00"},{"ClientName":"Name","RoomName":"Room 9","RoomFromTime":"07:00:00","RoomToTime":"23:00:00"},{"ClientName":"Name","RoomName":"Room 8","RoomFromTime":"07:00:00","RoomToTime":"23:00:00"},{"ClientName":"Name","RoomName":"Room 7","RoomFromTime":"07:00:00","RoomToTime":"23:00:00"},{"ClientName":"Name","RoomName":"Room 5","RoomFromTime":"07:00:00","RoomToTime":"23:00:00"},{"ClientName":"Name","RoomName":"Room 3","RoomFromTime":"07:00:00","RoomToTime":"23:00:00"},{"ClientName":"Name","RoomName":"Room 4","RoomFromTime":"08:00:00","RoomToTime":"23:00:00"},{"ClientName":"Name","RoomName":"Room 15","RoomFromTime":"08:00:00","RoomToTime":"19:00:00"}]
My JQuery function has the following:
$(document).ready(function () {
var json = $.getJSON("get_data.php", function(data){
var tr ;
for (var i = 0; i < json.length; i++) {
tr = $('<tr/>');
tr.append("<td><div class='clientname-text'>" + json[i].ClientName + "</div></td>");
tr.append("<td><div class='roomname-text'>" + json[i].RoomName + "</div></td>");
tr.append("<td><div class='time-text'>" + json[i].RoomFromTime + " - " + json[i].RoomToTime + "</div></td>");
$('table').append(tr);
}
});
});
Using the call to the other php script does not display the returned data in the table. Now I know I have gone wrong somewhere, but can anyoe see what I am doing incorrectly.
Many thanks in advance for your time.
UPDATE:

Because getJSON by default works asynchronously, the json variable is not filled at the time the callback is run. Change the callback to:
$.getJSON("get_data.php", function(json){
...
It appears there is a wrapper around your actual jason.
Either fix it like this:
$.getJSON("get_data.php", function(json){
json = json[0].data;
...
or fix it in get_data.php.

You can use this 100% working code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("get_data.php", function(data){
$.each(data, function(i, field){
var tr ;
tr = $('<tr/>');
tr.append("<td><div class='clientname-text'>" + field.ClientName + "</div></td>");
tr.append("<td><div class='roomname-text'>" + field.RoomName + "</div></td>");
tr.append("<td><div class='time-text'>" + field.RoomFromTime + " - " + field.RoomToTime + "</div></td>");
$('table').append(tr);
});
});
});
</script>
</head>
<body>
<table></table>
</body>
</html>

Related

Hot to get PHP variables in JSON format and refresh by AJAX

I have a device which export data in XML format.
And I would like to display this data on my webpage + refresh every second by ajax.
So my PHP file is:
<?php
$xml=simplexml_load_file("http://admin:pass#192.168.0.109/st0.xml") or die("Error: Cannot create object");
echo json_encode($xml);
exit();
this will display:
{"out0":"1","out1":"1","out2":"1","out3":"1","out4":"1","out5":"1","out6":"1","di0":"up","di1":"up","di2":"up","di3":"up","ia0":"473","ia1":"166","ia2":"359","ia3":"187","ia4":"4326","ia5":"1832","ia6":"36","ia7":"198","ia8":"6","ia9":"234","ia10":"-600","ia11":"246","ia12":"-600","ia13":"0","ia14":"0","ia15":"65952","ia16":"0","ia17":"854000","ia18":"1000","ia19":"192","freq":"5008","duty":"500","pwm":"0","sec0":"27","sec1":"17","sec2":"20","sec3":"1","sec4":"1481894628"}
So now I know how to display whole data and refresh, but I do not now how to put every data in separete div, ex. to display only interesting part:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
setInterval(function() {
$("#load_results").load("get_xml.php");
}, 1000);
});
</script>
</head>
<body>
<div id = "load_results"></div>
</body>
</html>
You have 2 situations:
Either you know the format of the JSON and you can build a DOM
structure using jQuery (for example) in the exact format you want
with the exact data you have.
For that you will have to access the object properties of the JSON object so for instance:
$("#load_results").load("get_xml.php");
becomes:
$.get( "get_xml.php", function( data ) { // retrieves the JSON from that file using AJAX
var parsedJSON = JSON.parse(data); // we convert the JSON string into a Javascript object
var formattedString = 'Our OUT0 is ' + parsedJSON.out0 + '<br>'; // we access the data in the Javascript object as for all Javascript objects, see http://www.w3schools.com/js/js_objects.asp
formattedString = formattedString + 'Our ia12 is ' + parsedJSON.ia12; // and so on
$('#load_results').html(formattedString);
});
Either you don't know the format or
you don't care at all. In this case the situation is simpler, you
can use a JSON prettifying tool for JavaScript such as the one
implemented here: http://jsfiddle.net/unLSJ/ (by someone else than me, cheers to him).
For the option 2 this would be the library:
// Library
window.jsonPrettifier = {
replacer: function(match, pIndent, pKey, pVal, pEnd) {
var key = '<span class=json-key>';
var val = '<span class=json-value>';
var str = '<span class=json-string>';
var r = pIndent || '';
if (pKey)
r = r + key + pKey.replace(/[": ]/g, '') + '</span>: ';
if (pVal)
r = r + (pVal[0] == '"' ? str : val) + pVal + '</span>';
return r + (pEnd || '');
},
prettyPrint: function(obj) {
var jsonLine = /^( *)("[\w]+": )?("[^"]*"|[\w.+-]*)?([,[{])?$/mg;
return JSON.stringify(obj, null, 3)
.replace(/&/g, '&').replace(/\\"/g, '"')
.replace(/</g, '<').replace(/>/g, '>')
.replace(jsonLine, library.json.replacer);
}
};
After you added this library somewhere inside your code, you can replace
$("#load_results").load("get_xml.php");
with
$.get( "get_xml.php", function( data ) { // retrieves the JSON from that file using AJAX
var parsedJSON = JSON.parse(data);
$('#load_results').html(window.jsonPrettifier.prettyPrint(parsedJSON));
});
and you will obtain a pretty printed JSON.

jquery ui datepicker not working with tabs

When a user switches tabs in the jquery ui code they can click on a button to add data to a jqgrid. The only thing that is not working is datepicker; it will launch one time and after that when switching to a new tab it will not launch again.
source document code;
<link href="/Includes/Site.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="/Includes/jqgrid/css/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="/Includes/jqgrid/src/css/ui.jqgrid.css">
<script src="/Includes/jqgrid/js/jquery-2.1.4.min.js"></script>
<script src="/Includes/jqgrid/css/jquery-ui-1.11.4.min.js"></script>
<script src="/Includes/jqgrid/js/i18n/grid.locale-en.js"></script>
<script src="/Includes/jqgrid/js/jquery.jqGrid.min.js"></script>
<script src="/Includes/validation/dist/jquery.validate.min.js"></script>
<script src="/Includes/validation/dist/additional-methods.min.js"></script>
$("#tabs").tabs(
{
//each tab activation
activate:function(event, ui)
{ loadGrid(); },
beforeActivate:function(event, ui)
{
var curTab = $('#tabs .ui-tabs-active');
var curTabName = curTab.text();
var pos = curTabName.search('-');
var curID = curTabName.slice(0,pos);
var passFrmDiv = "div[id^=adddaydata" + curID + "]";
$(passFrmDiv).html("");
}
});
function loadGrid()
{
var curTab = $('#tabs .ui-tabs-active');
var curTabName = curTab.text();
var pos = curTabName.search('-');
var newID = curTabName.slice(0,pos);
//reset adddaydata
$("div[id^=adddaydata" + newID + "]").text('');
//load form
var getFrmURL = '90daywellform.php?id=' + newID + '&d=' + $.now();
var passFrmDiv = "div[id=wellform" + newID +"]";
$.get(getFrmURL, function(data)
{ $(passFrmDiv).html(data); });
//$(passFrmDiv).load('90daywellform.php?id=' + newID + ' #loadform');
//load grid
var getGrdURL = '90daygrid.php?id=' + newID + '&d=' + $.now();
var passGrdDiv = "div[id=jqgrid" + newID +"]";
$.get(getGrdURL, function(data)
{ $(passGrdDiv).html(data); });
//$(passGrdDiv).load('90daygrid.php?id=' + newID);
};
//date picker function for adding wells info
$("button[id^=addday]").click(function()
{
var curTab = $('#tabs .ui-tabs-active');
var curTabName = curTab.text();
var pos = curTabName.search('-');
var newID = curTabName.slice(0,pos); //id of the current well
//var dtTag = '#datepicker' + newID;
$.get('get90maxday.php?id=' + newID,
function(data)
{
var passMax = data;
var getFrmURL = '90dayadddayform.php?id=' + newID + '&maxday=' + passMax + '&d=' + $.now();
var passFrmDiv = "div[id^=adddaydata" + newID + "]";
$.get(getFrmURL, function(data)
{ $(passFrmDiv).html(data); });
//$().text(newID + " " + passAPI);
//$("#gridarea").load('scadagrid.php?api=' + passAPI + '&start=' + passStart + '&end=' + passEnd);
}
);
});
And here is the code from the dynamic document that is being loaded;
<?php
$id = $_GET['id'];
?>
<link href="/Includes/Site.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="/Includes/jqgrid/css/jquery-ui.css">
<script src="/Includes/jqgrid/js/jquery-2.1.4.min.js"></script>
<script src="/Includes/jqgrid/css/jquery-ui-1.11.4.min.js"></script>
<script src="/Includes/validation/dist/jquery.validate.min.js"></script>
<script src="/Includes/validation/dist/additional-methods.min.js"></script>
<tr>
<td><label for="dt<?php echo $id; ?>">Date</label></td>
<td><input id="dt<?php echo $id; ?>" name="dt<?php echo $id;?>" type="text"></td>
</tr>
var passID = $("input[id^=id]").val();
var dtPkr = "input[id=dt" + passID +"]";
$(dtPkr).datepicker();
Any assistance is greatly appreciated
You're going to want to tap into the activate event if you've got this hosted in a tab (don't see it in the code, but it's in the question?). See jQuery UI Tabs Widget documentation.
You're going to want to add, in activate or in your loadGrid() function, something to initialize the datepickers:
$(".datepicker").datepicker();
You would, of course, have to have the datepickers be of class datepicker for that to work. See jQuery UI Datepicker documentation.

Passing JSON from PHP to a JavaScript variable

I'm making an aplication with phonegap and I'm stuck trying to send JSON data from the PHP on the server to JavaScript on the device. I want to do something like:
var JSON = '{ "Table" : ' + "http://www.hel.net/LoadDB.php=?table=exhibitions" + '}';
the php works fine and returns somethig like:
"[{"id":"1","name":"Art for everyone","image":null,"name2":"June 29, 2013: 11:00am.","description":"With reservation\r\nFree entrance","description2":null}]"
I want that result in a javascript variable to work later with:
var obj = eval ("(" + JSON + ")");
document.getElementById("rName").innerHTML=obj.Table[1].name;
document.getElementById("lname").innerHTML=obj.Table[1].name2;
What I want to do is something like:
var JSON = '{ "Table" : ' + "http://www.hel.net/LoadDB.php=?table=exhibitions" + '}';
var obj = eval ("(" + JSON + ")");
document.getElementById("rName").innerHTML=obj.Table[1].name;
document.getElementById("lname").innerHTML=obj.Table[1].name2;
How can I make the first line work? is it possible to make the first line work?
PS. I do not have much experience with JSON arrays.
Ok I tried ajax and works, I used:
console.log("before");
var jqxhr = $.ajax( "http://www.hel.com/LoadDB.php?table=exhibitions" )
.done(function(data) { console.log(data); })
.fail(function() { console.log("error"); })
.always(function() { console.log("complete"); });
console.log("after");
more info in:
api.jquery.com
I think all you need is var obj = <?php echo $myjsonencodedvar; ?>
or
var obj = <?php echo json_encode($myarray_or_object); ?>
Since I said "I think..." I decided to test it out. I found the following dump() function here on SO.
$arr=array(1,'biscuit'=>'gravy',3,4,5);
$json=json_encode($arr);
?>
<script>
j=<?php echo $json; ?>;
document.write(dump(j));
function dump(obj) {
var out = '';
for (var i in obj) {
out += i + ": " + obj[i] + "\n";
}
return out;
}
</script>
output:
0: 1 biscuit: gravy 1: 3 2: 4 3: 5
Try this:
PHP: (json.php)
<?php
header("Content-Type: text/json");
//the data format your question mentioned
$data = array("Table"=>array(array("id"=>"1","name"=>"Art for everyone","image"=>null,"name2"=>"June 29, 2013","description"=>"With reservation\r\nFree entrance","description2"=>null)));
echo json_encode($data);
?>
Front-end:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$.get("json.php",function(json){
alert(json.Table[0].name);
});
</script>
</body>
</html>
Hope this is helpful for you.
using JSONP (no callbacks), and on the client side use $.getJSON() it will parse it from json string to js object.

getJSON - why it didnt work?

Why getJSON method works only with local files? If I want to take json from local it works, but if I set url with http it doesnt work. why?
<!DOCTYPE html>
<html>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<script>
$.getJSON("http://www.address.com/getTables.php", function (data) {
$.each(data, function (i, table) {
$("#tables").append("<p>" + table.id + " " + table.tabname + "</p>");
});
});
</script>
<body>
<div id="tables"></div>
</body>
</html>
Returned JSON:
[{ "id":"12", "tabname":"cukry" }, { "id":"11", "tabname":"table" }]
It sounds like you're probably running into the same-origin policy.
Like Matt said it`s because of the same origin policy. Try using JSONP. You just need to add callback to your request URL like this:
$.getJSON("http://www.address.com/getTables.php?jsoncallback=?", function (data) {
$.each(data, function (i, table) {
$("#tables").append("<p>" + table.id + " " + table.tabname + "</p>");
});
});
See more about JSONP here

PHP Script with Arguements to AJAX Auto Refresh

I would like to create a PHP page which accepts an arguement like so:
http://localhost/page.php?topic=Foo
and then pulls data from an SQL Database where topic=Foo but then automatically checks for new data every 10 seconds and refreshes a DIV tag using Ajax. I've tried and nothing works. Any help?
EDIT: here is the code I've used:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
ext = <?php $_GET[feedtitle] ?>
$(document).ready(function() {
$("#responsecontainer").load("response.php?ext=" + ext);
var refreshId = setInterval(function() {
$("#responsecontainer").load('response.php?ext=' + ext);
}, 9000);
$.ajaxSetup({ cache: false });
});
</script>
</head>
<body>
<div id="responsecontainer">
</div>
</body>
EDIT: I can do the SQL bit, it's just the getting the arguement to the response.php im having issues with.
EDIT: I have new code, but its still not working:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function gup( name )
{ name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
var feed = gup('f');
$(document).ready(function() {
$("#responsecontainer").load("response.php?ext=" + feed);
var refreshId = setInterval(function() { $("#responsecontainer").load('response.php? ext=' + feed); }, 9000);
$.ajaxSetup({ cache: false });
});
</script>
</head>
<body>
<div id="responsecontainer">
</div>
</body>
So, you need to
Get escaped URL parameter
,
output the jquery $.post function's result data and then you just need to know
How to refresh page with jQuery Ajax? and do an
AJAX Div Retrieval every 60 seconds?
I hope that helps :)

Categories