Returning PHP array to Javascript array - php

I am trying to return my SQL query array into a javascript array and then display the info one at a time. I have found a few helpful posts already on here but I still cannot get it to work. I am new to ajax and so please forgive any stupid mistakes. Below is the php followed by a description.
php: this is in an external file from index.php
<?php
include('connection.php');
$query = "SELECT * FROM photos";
$queryresult = mysql_query($query);
while ( $line = mysql_fetch_array($result) ) {
$path[] = $row[0];
}
$paths = json_encode($path);
header('Content-type: application/json');
echo $paths;
?>
This gets the results (they are file paths) array and json encodes them to pass to javascript. Connection.php is correct and it is working.
HTML/Javascript:
<html>
<head>
<script src="JavaScript/gjs.js" type="text/javascript"></script>
<script src="jquery/jquery-1.4.3.min.js" type="text/javascript"></script>
<script>
function imageload(){
var i = 1;
$.getJSON('phpfiles/getpiccode.php', function(data) {
var can = document.getElementById('canvas').getContext('2d');
$.each(data,function(idx, row){
var img = new Image();
img.onload = function(){
can.drawImage(img, 0, 0, 1280, 800);
}
img.src = row;
i++;
});
});
}
</script>
</head>
<body>
<div class="container">
<canvas id="canvas" class="canvas-one" width="1280" height="800">
<script>imageload();</script>This text is displayed if your browser does not support HTML5 Canvas</canvas>
</div>
</body>
</html>
I hope that makes sense. Thanks again!

Use json_encode() to encode it as JSON.
In recent browsers you can simply turn the string from that function into a JavaScript object using var obj = JSON.parse(yourstring); - but better use e.g. jQuery for AJAX and JSON parsing.
Update: Your JavaScript should looke like that to iterate over the data from your query:
$.getJSON('phpfiles/getpiccode.php', function(data) {
// get canvas object. it's the same for all images so only do it once
var can = document.getElementById('canvas').getContext('2d');
// iterate over the elements in data
$.each(data, function(idx, row) {
var img = new Image();
img.onload = function() {
can.drawImage(img, 0, 0, 1280, 800);
}
img.src = row;
});
});
However, it might not do what you want: It will draw all images pretty much at once at the same position.
Also replace <script>imageload() </script> (assuming that's the function containing your JavaScript) with <script type="text/javascript">imageload();</script> as that's the correct/proper syntax.
In your PHP code you'll have to replace return $paths; with echo $paths; unless you are using some framework which relies on your file returning something. Additionally it'd be good to send a JSON header: header('Content-type: application/json');
PS: SELECT * combined with MYSQL_NUM is a BadThing. It relies on the columns in the table having a certain order. If you just need one column use "SELECT columnName"; if you need all, use MYSQL_ASSOC to get an associative array.

Related

How to print JSON array inside script tag?

I'm trying to display JSON array inside <script> tag, is that possible?
Here is what I've tried so far:
<script>
var x = JSON.stringify(data);
var json = (function() {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': "empdata.json",
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
})();
</script>
What I'm trying to do:
<script>
var videos = {"employee_id":"1","employee_name":"Steve","designation":"VP","hired_date":"2013-08-01","salary"
:"6000"};
</script>
Yea you just echo it like this, assuming you have an $array of parameters like array("employee_id"=>1 ... )
var videos = <?php echo json_encode(array(
"employee_id"=>1
)); ?>; // <- don't miss the java-script semi-colon though
This should just print
var videos = {"employee_id":1};
PHP doesn't care where you echo it at, in your page, it doesn't have a concept about what a <script> tag is. All it knows is some things are php code, everything else is string content.
OR you could just do this
var videos = <?php echo '{"employee_id":1}'; ?>;
But that is kind of pointless, unless you mean like this.
var videos = <?php echo '{"employee_id":'.$employee_id.'}'; ?>;
Or you can do this way to
var videos = {"employee_id":1};
And just put it in there, I don't understand anymore?
If you mean from a file containing your json, then sure.
<?php
$json = file_get_contents( 'pathtofile.json');
?>
<script> ... etc.\
var videos = <?php echo $json; ?>;
PHP can read files, and it can echo the contents of those files, PHP doesn't care whats in them. The only catch is the content has to be valid Json for the javascript to work. But php doesn't care if it's JSON, XML, Binary etc. it's all text because PHP is a loosely typed language. In fact php doesn't care if your Javascript works, it has no concept of what javascript is.
In fact this works too ( assuming image.jpg is a real image file. ).
$jpg = file_get_contents( 'image.jpg' );
echo '<img src="'. $jpg.'" \>
OR
header('Content-Type: image/jpeg');
echo file_get_contents( 'image.jpg' ); //assuming there is no other content

multiple highcharts on one page

I'm wishing to render multiple charts using mysql data, there will be more or less charts depending on a particular search. I've successfully created a single chart, and my php file echoes the required json format nicely.
Now, what I would like is to be able to loop over an array and draw new charts based on the array vales being parsed to the php which in turn provides different json data to be rendered.
by the way, my javasript is very limited so here goes my code and thoughts:
<script type="text/javascript">
$(function () {
var chart;
var venue = <?php echo json_encode($venue_name); ?>; /* parsed to php file */
var distances = <?php echo json_encode($data); ?>; /* array to be looped over */
$(document).ready(function() {
var options = {
....
series: []
....
};
//
$.each(distances, function() {
$.each(this, function(name, value) {
// do some ajax magic here:...
GET 'myphpfile.php?venue='+venue+'&'+distances
function drawNewChart(){
$('#mainSite').append('<div id="container" style="float:left; display:inline"></div>');
chart = new Highcharts.Chart(options);
});
});
</script>
What I have learnt is that I cannot loop an include php file which has the completed php and jquery...
this will create other charts. every time u want create new chart , u must give new name chart like i do chart2
paste this bellow and it will give you other chart.
<script type="text/javascript">
$(function () {
var chart2;
var venue2 = <?php echo json_encode($venue_name); ?>; /* <---use other variable here of $venue_name */
var distances2 = <?php echo json_encode($data); ?>; /* <---use other variable of $data */
$(document).ready(function() {
var options = {
....
series: []
....
};
//
$.each(distances2, function() {
$.each(this, function(name, value) {
// do some ajax magic here:...
GET 'myphpfile.php?venue2='+venue2+'&'+distances2
function drawNewChart(){
$('#mainSite').append('<div id="container" style="float:left; display:inline"></div>');
chart2 = new Highcharts.Chart(options);
});
});
</script>
Instead of using many variables, you can push your charts to array.
var charts = [];
charts.push(new Highcharts(options));
Then you can avoid of using index etc.

Reading latitude/longitude from DB and putting markers on the map

Below is given my sample code. In index.php I define jquery tabs. One of the tabs should open a map (openlayers) and put markers on this map. Latitude and longitude of each marker is taken from MySQL DB. The problem is that I don't know how and where to execute the function put_marker reading data from DB. I know it should be a basic question.
index.php
<script type="text/javascript">
$(document).ready(function() {
$("#tabs").tabs({
ajaxOptions: {
success: function( html ) {
$("#content").html(html);
page_init();
}
}
});
});
</script>
<div id="tabs">
<ul>
<li><span>Administration</span></li>
<li><span>Map</span></li>
</ul>
</div>
map.php
<?php
include_once 'include/DatabaseConnector.php';
$query4="SELECT r.resLatitude, r.resLongitude FROM resources r;";
$result4=DatabaseConnector::ExecuteQueryArray($query4);
foreach ($result4 as $row):
// HERE I HAVE A PROBLEM
//putMarker($row['resLatitude'],$row['resLongitude']);
endforeach;
?>
<script src="http://www.openlayers.org/api/OpenLayers.js"></script>
<script type="text/javascript">
var map, layer;
function page_init(){
map = new OpenLayers.Map("basicMap");
var mapnik = new OpenLayers.Layer.OSM();
var fromProjection = new OpenLayers.Projection("EPSG:4326"); // Transform from WGS 1984
var toProjection = new OpenLayers.Projection("EPSG:900913"); // to Spherical Mercator Projection
var position = new OpenLayers.LonLat(2.07833,41.2969).transform( fromProjection, toProjection);
var zoom = 15;
map.addLayer(mapnik);
map.setCenter(position, zoom );
}
function putMarker(latMarca, lonMarca)
{
var lonLat = new OpenLayers.LonLat(lonMarca ,latMarca ).transform(new OpenLayers.Projection("EPSG:4326"),map.getProjectionObject());
var zoom=16;
var markers = new OpenLayers.Layer.Markers( "Markers" );
map.addLayer(markers);
markers.addMarker(new OpenLayers.Marker(lonLat));
map.setCenter (lonLat, zoom);
}
</script>
<div id="basicMap" style="width: 100%; height: 100%;">
</div>
Well, you're getting your markers in PHP on the server side. And you're passing them to Javascript on the client side. Two different places.
Actually, there's no need even in JSON manipulations in the simplest case.
In your map.php you can do:
..
echo '<script type="text/javascript">';
echo '$(document).ready(function() {';
foreach ($result4 as $row){
echo 'putMarker('.$row['resLatitude'].','.$row['resLongitude'].');';
}
echo '});';
echo '</script>';
...
These code would be interpreted on the client side as pure JS, but with values being taken from the PHP.
By the way, it's not a good approach to write your code the same way.
Look toward MVC frameworks, where the code and look are separated from each other.

Pass JSON from php to javascript

I want to localize my webapp. Since localization through javascript only is not recommended I thought using php would be an alternative.
So with php I read a messages.json file that stores all localization data.
$json = file_get_contents("_locales/en/messages.json");
In the header of my webapp I generate some javascript with php according to the user's browser language.
echo "var localeObj = " . $json . ";";
So this is just a var that holds all data from the messages.json file that looks like that
{
"extTitle": {
"message": "Test1"
},
"extName":{
"message": "Test2"
}
}
Now I want to be able to access each item from the json like
var title = getItem("extTitle");
and it returns Test1. Any idea how to do that?
I am not very familar with json but if I just alert the localeObj it gives me just [object Object].
var getItem = function(item) {
return localObj[item].message;
};
You could always encapsulate your i18n strings too...
(function() {
var localObj = { ... };
window.getItem = function(item) {
return localObj[item].message;
};
})();
This way, no other variables can possibly clobber your localObj.
You use array syntax [], or dot syntax ., to access javascript object properties.
Example:
localeObj["extTitle"];
localeObj.extTitle;
I would recommend reading something like this to get more familier with JSON.
You can initialize javascript variable like this.
var json = eval(<? echo $json ?>);
alert(json.extTitle.message+ ' '+json.extName.message);
Inside messages.php:
<?php
header('Content-type:application/javascript');
$messages = array(
"yes"=>"hai",
"no"=>"iie"
);
$messages = json_encode($messages);
echo "window.messages = $messages";
?>
Inside index.html:
<html>
<body>
<script type="text/javascript" src="messages.php"></script>
<script type="text/javascript">
console.log(window.messages)
</script>
</body>
</html>
As long as you tell the browser to interpret the php file as a javascript file, you can echo anything you want.

how to return multiple array items using json/jquery

Hey guys, quick question, I have a query that will usually return multiple results from a database, while I know how to return one result, I am not sure how to return multiple in jquery. I just want to take each of the returned results and run them through my prepare function. I have been trying to use 'for' to handle the array of data but I don't think it can work since I am returning different array values. If anyone has any suggestions, I would really appreciate it.
JQUERY RETRIEVAL
success: function(json) {
for(i=0; i < json.rows; i++) {
$('#users_online').append(online_users(json[i]));
$('#online_list-' + count2).fadeIn(1500);
}
}
PHP PROCESSING
$qryuserscount1="SELECT active_users.username,COUNT(scrusersonline.id) AS rows FROM scrusersonline LEFT JOIN active_users ON scrusersonline.id=active_users.id WHERE topic_id='$topic_id'";
$userscount1=mysql_query($qryuserscount1);
while ($row = mysql_fetch_array($userscount1)) {
$onlineuser= $row['username'];
$rows=$row['rows'];
if ($username==$onlineuser){
$str2= "<div class=\"me\">$onlineuser</div>";
}
else {
$str2= "<b><div class=\"others\">$onlineuser</div></b>";
}
$data['rows']=$rows;
$data['entry']=$str1.$str2;
}
EDIT ONLINE USERS FUNCTION
function online_users(response) {
count2++;
var string = '<div class="update-entry"><li id="online_list-'+count2+'">'
+ ''+response.entry+''
+'</li></div>';
return string;
}
Hopefully this will help you get pointed in the right direction:
foo.php
<html>
<head>
<script type="text/javascript" src="user_list.js"></script>
<style type="text/css" media="screen">
/* instead of using html tags for markup, use CSS */
#users_online .me {}
#users_online .other { font-weight: bold; }
</style>
</head>
<body>
<div id="content">foo</div>
<div id="users_online">
<div class="count"></div>
<div class="list"></div>
</div>
</body>
</html>
user_list.js
<script type="text/javascript" charset="utf-8">
(function($){
var refresh_user_list = function(){
// get the data
$.getJSON("/user_list.php", function(data)){
// insert HTML into DOM
$("#users_online .count").html(data['count']);
$("#users_online .list").html(data['users']);
};
// refresh users list again every 15 seconds
setTimeout(refresh_user_list, 15000);
};
// after the page is ready, get the user list
$(document).ready(function(){
refresh_user_list();
});
})(jQuery);
</script>
user_list.php
<?php
// header
header("Content-Type: application/json");
// return data
$data = array(
"users" => "",
"count" => 0
);
// query users
$result = mysql_query("
SELECT
active_users.username,
COUNT(scrusersonline.id) AS rows
FROM scrusersonline
LEFT JOIN active_users ON scrusersonline.id=active_users.id
WHERE topic_id='$topic_id';
");
// load users
while($u = mysql_fetch_object($result)){
$link_class = ($username == $u->username)
? "me"
: "other"
;
// don't use <b> tag here. define bold in the stylesheet with the link's class
$data["users"] .= "<a class=\"${link_class}\" href=\"statistics.php?user={$u->username}\">{$u->username}</a>";
}
// load count
// this is sort of silly, but I don't know the way your database is setup so it's hard to advise you how to improve it
$data["count"] = $u->rows;
// return the result
echo json_encode($data);
// make sure you stop the script here so nothing else gets output
exit;
?>
Why do you need to return multiple results? For something as simple as that, just format everything on the server-side and return all the HTML at once, then have jQuery just put it in. Don't make the client-side have to process things because it will likely be slower.

Categories