php code inside jquery function to read json file - php

I have a myfile.jsonfile like this:
[{"teamA": {"name": "DAR", "games": "4", "season":"RS", "points": "89"}},
{"teamB": {"name": "BAR", "games": "3", "season":"RS", "points": "78"}}]
I usually read the myfile.jsonfile like this:
$mydata=file_get_contents("myjsonfiles/myfile.json");
$decodeddata = json_decode($mydata,true);
So that I can use it in php. For example:
<?php
$teamApoints=$decodeddata["teamA"]["points"];
$teamBpoints=$decodeddata["teamB"]["points"];
$totalpoints=$teamApoints+$teamBpoints;
?>
<div class="apoints"><?php echo $teamApoints; ?></div>
<div class="bpoints"><?php echo $teamBpoints; ?></div>
<div class="totpoints"><?php echo $totalpoints; ?></div>
Now, the problem. I am very new at javascript functions, and I want to use the constantly changing info of the myfile.jsonfile to update the page without reloading it.
Some users gave me the idea, but, as a newcomer, it is difficult for me to implement it:
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<script>
function updatePage() {
$.getJSON('myjsonfiles/myfile.json', function(data) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
jQuery("body").html("");
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
}
setInterval(updatePage, 5000);
</script>
As this is incorrect, how could I access to the elements of the myfile.json inside js function and use them in php? Or, in case this is not possible, how could I access to the elements of the myfile.jsonfile and replace the content of the divs?
Thanks

Please try this approach:
<html>
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<script type="text/javascript">
function updatePage() {
$.getJSON('myfile.json', function(data) {
var $string = '';
var sum=0;
$.each( data, function( key, val ) {
var x= Object.keys(val);
sum += parseInt(val[x]["points"]);
$string += "<div class='"+x+"'>"+x+" Points:" + val[x]["points"] + "</div>" ;
});
$string += "<div class='totpoints'>Total Points:"+sum+"</div>"
jQuery("body").html($string);
});
}
jQuery(document).ready(function() {
setInterval(updatePage, 1000);
//set your time as per requirement, so that after this time interval data will update automatically
});
</script>
<body></body>
</html>

Related

How to use foreach loop in php for retrieve data from data base to jquery-ui accordion

How to use foreach loop in php for retrieve data from data base to jQuery-ui accordion. I want to user jQuery accordion for fetch data from database. I tried many ways but I can't to do that because of lack of my knowledge. I used jQuery-ui for this one.
This is the code I wrote for this
<body>
<div class="container" style="width:900px;">
<div id="accordion"></div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$.ajax({
url: "fetch.php",
method:"POST",
dataType: "json",
success: function(data)
{
console.log(data);
$( function() {
$( "#accordion" ).accordion();
//console.log(data);
var device_ID;
var sensor_ID;
} );
}
});
});
</script>
This is the PHP part:
<?php
//fetch.php
$connect = mysqli_connect("localhost", "root", "", "kapra_iot");
$query = "
SELECT * FROM `view_sensor`
";
$result = mysqli_query($connect, $query);
//$output = array();
while($row = mysqli_fetch_array($result))
{
$sub_data["device_ID"] = $row["device_ID"];
$sub_data["device_Name"] = $row["device_Name"];
$sub_data["sensor_ID"] = $row["sensor_ID"];
$sub_data["sensor_Name"] = $row["sensor_Name"];
$sub_data["lower_Value"] = $row["lower_Value"];
$sub_data["mid_Value"] = $row["mid_Value"];
$sub_data["upper_Value"] = $row["upper_Value"];
$data[] = $sub_data;
}
foreach($data as $key => &$value)
{
$output[$value["device_ID"]] = &$value;
}
foreach($data as $key => &$value)
{
if($value["sensor_ID"] && isset($output[$value["sensor_ID"]]))
{
$output[$value["sensor_ID"]]["nodes"][] = &$value;
}
}
foreach($data as $key => &$value)
{
if($value["sensor_ID"] && isset($output[$value["sensor_ID"]]))
{
unset($data[$key]);
}
}
echo json_encode($data);
//echo '<pre>';
//print_r($data);
//echo '</pre>';
?>
I'd point you to the docs just as Kumar Praveen did. The Accordion will display the different sections titles using the h3 tag and the inner section of each one inside div tags.
Loop trough the result and add it to your accordion div following the syntax described before.
$(document).ready(function () {
$.ajax({
url: "fetch.php",
method: "POST",
dataType: "json",
success: function (data) {
for (device in data)
{
$("#accordion").append("<h3>"+device['device_id']+" " + device['device_Name'] + "</h3>");
$("#accordion").append("<div><p> Insert here all the relevant data of your device including all the other variables</p></div>");
}
$("#accordion").accordion();
}
});
});
Using the Widget Factory, you can extend accordion to a remote source.
$(function() {
var testData = [{
"device_ID": 1001,
"device_Name": "Device 1",
"sensor_ID": 597,
"sensor_Name": "Sensor 1",
"lower_Value": 0,
"mid_Value": 50,
"upper_Value": 100
}, {
"device_ID": 1002,
"device_Name": "Device 2",
"sensor_ID": 598,
"sensor_Name": "Sensor 1",
"lower_Value": 0,
"mid_Value": 500,
"upper_Value": 1000
}, {
"device_ID": 1003,
"device_Name": "Device 3",
"sensor_ID": 599,
"sensor_Name": "Sensor 1",
"lower_Value": 0,
"mid_Value": 0.05,
"upper_Value": 0.1
}];
$.widget("custom.buildList", $.ui.accordion, {
options: $.extend(this.options, {
source: "",
data: []
}),
_create: function() {
console.log("Init");
this.element.addClass("custom-list");
var action;
if (this.options.source == "") {
action = "html";
} else if (typeof this.options.source == "string") {
action = "ajax";
} else {
action = "array";
}
console.log("Action", action);
if (action !== "html") {
if (action === "ajax") {
this.options.data = this._getData(this.options.source);
}
this._makeList(this.element);
}
console.log("Return to _create");
return this._super();
},
_getData: function(url) {
console.log("Getting Data", url);
$.getJSON(url, function(resp) {
this.options.data = resp;
});
},
_makeList: function(tObj) {
console.log("Making List");
var myData;
if (this.options.data.length == 0) {
myData = this.options.source;
} else {
myData = this.options.data;
}
console.log("List Data", myData);
$.each(myData, function(i, d) {
var hd = $("<h3>").html(d.device_Name);
var bd = $("<div>");
var ls = $("<ul>").appendTo(bd);
$.each(d, function(k, v) {
$("<li>").html(k + ": " + v).appendTo(ls);
});
tObj.append(hd, bd);
});
}
});
$("#accordion").buildList({
source: testData
});
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="container" style="width:900px;">
<div id="accordion"></div>
</div>
This extension allows a URL or Array to be passed in as a Source option. So if you wanted to use it to get data from a PHP Script, you could do:
$("#accordion").buildList({
source: "fetch.php"
});
The extended widget will collect the data from the URL or Array and build the needed HTML before calling on the rest of the widget. I had to test with an array. You will also need to modify _makeList() function to meet you various needs.
It is also built to default back to HTML if you so choose. Also you have all the same options as you would with a standard Accordion widget.

JSON, PHP & SQL implementation error

I'm trying to work out how to use JSON, php and SQL (initially MSSQL) to populate a type-ahead field of names and, once the name is selected, to also populate a job title and department. This is my first time to use JSON, so I'm starting a bit from scratch here.
I got a partial solution from Experts Exchange (see Fiddle) using static data, but I'm having trouble converting the data I'm pulling from the database to what is being shown in the fiddle.
The code for the fiddle is:-
<!DOCTYPE html>
<html>
<head>
<title>Autocomplete Textbox Demo | PHP | jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function() {
var availableTags = [{
empName: "A1",
empTitle: "AAA1 AAAAA"
}, {
empName: "A2",
empTitle: "AAA2 AAAAA"
}, {
empName: "B",
empTitle: "AAA AAAAA"
}, {
empName: "C",
empTitle: "AAA AAAAA"
}];
var empNames = [];
var empTitles = [];
$(availableTags).each(function(ix, v) {
empNames.push(v.empName);
empTitles.push(v.empTitle);
});
$("#empName").autocomplete({
source: empNames,
autoFocus: true,
select: function(event, ui) {
//console.log(event);
//console.log(ui);
//console.log(getTitle(ui.item.label));
$("#empTitle").val(getTitle(ui.item.label));
}
});
$("#empTitle").autocomplete({
source: empTitles,
autoFocus: true,
select: function(event, ui) {
//console.log(event);
//console.log(ui);
//console.log(getName(ui.item.label));
$("#empName").val(getName(ui.item.label));
}
});
function getName(t) {
//console.log("title:" + t);
for (k in availableTags)
if (availableTags[k].empTitle == t) return availableTags[k].empName;
};
function getTitle(n) {
//console.log("name:" + n);
for (k in availableTags) {
//console.log("k:" + availableTags[k].empName + " > " + availableTags[k].empTitle);
if (availableTags[k].empName == n) return availableTags[k].empTitle;
}
};
});
</script>
</head>
<body>
<label>Department Name</label></br>
<input id="empName" type="text" size="50" /><br>
<input id="empTitle" type="text" size="50" />
</body>
</html>
I'm stuck now on implementing the results returned from the database query to work with the fiddle. I believe I've to the data correctly formatted but it's wrong somewhere and I'm not sure where that is.
I'm getting the data from an SQL table with a separate php page called fetchEmpName.php:-
<?php
require('i_PDOConnection.php');
$query = "SELECT empFName + ' ' + empLName as [empName], empTitle, empDept FROM tbl_CouncilStaff WHERE active = 1 AND display = 1 AND (empFName LIKE '%".$search."%' OR empLName LIKE '%".$search."%') ORDER BY empLName";
$stmt = $dbh->prepare($query);
$stmt->execute();
$data = $stmt->fetchAll();
$return_arr = array();
$return_arr['contacts'] = array();
foreach ($data as $row) {
$dataArray['empName'] = $row['empName'];
$dataArray['empTitle'] = $row['empTitle'];
array_push($return_arr['contacts'],$dataArray);
}
echo json_encode($return_arr);
?>
Which (according to the Chrome console log, produces an array like:
{empName: "Bob Smith", empTitle: "Chief Cook and Bottle Washer"}
Which works properly when I replace the fiddle data with the generated data but fails once the static data is replaced by the sql code. So that tells me that the problem lies in the script. At this point, the page has morphed into:
<!DOCTYPE html>
<html>
<head>
<title>Autocomplete Textbox Demo | PHP | jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function() {
var availableTags = <?php include('fetchEmpName2.php'); ?>;
var empNames = [];
var empTitles = [];
$(availableTags).each(function(x, y) {
empNames.push(y.empName);
empTitles.push(y.empTitle);
});
$("#empName").autocomplete({
source: empNames,
autoFocus: true,
select: function(event, ui) {
// console.log(event);
// console.log(ui);
// console.log(getTitle(ui.item.label));
$("#empTitle").val(getTitle(ui.item.label));
}
});
$("#empTitle").autocomplete({
source: empTitles,
autoFocus: true,
select: function(event, ui) {
//console.log(event);
//console.log(ui);
//console.log(getName(ui.item.label));
$("#empName").val(getName(ui.item.label));
}
});
function getName(t) {
//console.log("title:" + t);
for (k in availableTags)
if (availableTags[k].empTitle == t) return availableTags[k].empName;
};
function getTitle(n) {
//console.log("name:" + n);
for (k in availableTags) {
//console.log("k:" + availableTags[k].empName + " > " + availableTags[k].empTitle);
if (availableTags[k].empName == n) return availableTags[k].empTitle;
}
};
console.log(availableTags);
});
</script>
</head>
<body>
<label>Department Name</label></br>
<input id="empName" type="text" size="50" /><br>
<input id="empTitle" type="text" size="50" />
</body>
</html>
When I run the page, the jquery library throws an error saying
jquery-ui.min.js:8 Uncaught TypeError: Cannot read property 'label' of undefined"
I hope this is enough for someone to sort out where I'm off track - or if there is a better way to solving the problem of filling additional fields from a type-ahead field.
Thanks in advance - any assistance offered would be greatly appreciated.

jquery $.getScript().. How to get data from external js file into array

I try to put data into js file, through "jquery $.post" and "fwrite php", and get back that data into array. How to do that?
here's the html:
<!doctype html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<script>
$(document).ready(function() {
$("#button").click(function() {
if ($("#nameput").val() != "") {
$.post("processing.php", {
putname: $("#nameput").val()
});
var arr = [$.getScript("talk.js")];
alert(arr[0]);
}
})
})
</script>
</head>
<body>
<input type="text" id="nameput" />
<button id="button">send AJAX req</button>
</body>
</html>
Here's the php, I name it "processing.php" :
<?php
$file = fopen("talk.js","a");
$text = $_POST["putname"];
fwrite($file,'"'.$text.'",');
fclose($file);
?>
And "talk.js" will look like this :
"a","b","c",
Why I can't put that data from "talk.js" into array at " var arr = [$.getScript("talk.js")]; " as in html file above?
Here's what I try after I read comments. I change the scirpt into this:
<script>
$(document).ready(function() {
$("#button").click(function() {
if ($("#nameput").val() != "") {
$.post("processing.php", {
putname: $("#nameput").val()
}, function() {
$.getScript("talk.js", function(data) {
var arr = data.split(",");
alert(arr[0]);
})
})
}
})
})
</script>
And php into this:
<?php
$file = fopen("talk.js","a");
$text = $_POST["putname"];
fwrite($file,$text);
fclose($file);
?>
But it still not work?
here's a simplified version of your button click to help you out:
$("#button").click(function() {
$.getScript("talk.js", function(data){
var arr = data.split(',');
alert(arr[0]);
});
});
If you log the output of $.getScript you will easily see why what you're trying doesn't work.
Using this method you will get the data returned from the script ("a","b","c"), but you'll need to split it on a comma into an array. Then you can reference whichever part of the array you want.
Note that the each element of the array will have quotations around them.

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.

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