I have a problem with my javascript array. Bellow my code:
$namen = array();
$mainimg = array();
$sql1 = mysql_query("SELECT * FROM image WHERE id = ".$id.";");
echo "<div class='normal'>";
while($row = mysql_fetch_array($sql1))
{
$namen[] = $row['bild'];
$mainimg[] = $row['mainimg'];
$number_array = count($namen);
?>
<script type='text/javascript'>
<?php
for($a=1; $a <= count($namen); $a++){
$php_array = array($a => $row['bild']);
$js_array = json_encode($php_array);
echo "var javascript_array = ". $js_array . ";\n";
echo "document.write(javascript_array + '<br />');";
}
?>
</script>
}
Now I get [object][Object] in the browser, but I wanted to printout the elements, the name of the pictures. What can I do?
Thanks for your help in advance.
Regards, Yanick
You're trying to print a Object as a string. What you need to do is to access your properties directly from the object.
<script>
<?php $data = array('foo' => 'bar'); ?>
var my_js_var = <?php echo json_encode($data); ?>;
</script>
With this script, you can access your values like this:
document.write(my_js_var.foo); // writes 'bar'
You'll need to loop through the array and output the fields you want for each item. You're currently printing out the string version of an object in JavaScript, which is always [object Object].
Related
I query my database with a PHP script that looks like this:
$query = "SELECT * FROM JKFactory WHERE ronde = '$ronde' AND moment = '$moment' AND klas = '$klas'";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['afzetAG'];
echo ",";
}
This gives a result something like this:
10000,20000,30000,
I need this data to build a piegraph with chart.js.
chart.js works with arrays for the data. So the numbers should be returned as an array which I can put into an JavaScript variable which I can use with chart.js.
Another problem is the last comma. I have no idea how I can get rid of this comma.
Maybe these question are straightforward but I am relatively new in this field I really get stuck on this part.
You have the array and you'd put the comma after the results yourself. so try to declare an array like $arr before while and use array_push($arr,$row['afzetAG']) inside the while
To print your result like 1000,2000,3000... You can save the content into an Array and print it using implode:
$data = array();
while($row = mysql_fetch_array($result))
{
array_push($data, $row['afzetAG']);
}
echo implode(",",$data);
But if you want to use an Array from PHP to JavaScript you can do this:
<script type="text/javascript">
<?php
$data = array();
while($row = mysql_fetch_array($result))
{
array_push($data, $row['afzetAG']);
}
?>
var obj = <?php echo json_encode($data); ?>;
</script>
So now obj contains the Array ready to use in your JavaScript code.
$types = array();
while(($row = mysql_fetch_assoc($result))) { $types[] = $row['type']; }
ok i made it. To echo the result i used this:
$a = array();
while($row = mysql_fetch_array($result))
{
$b = $row['afzetAG'];
array_push($a,$b);
}
echo implode(",",$a);
This gives not an array i can use in javascript. In javascript i put the result in a variable myResult and than i used:
myResult = myResult.split(',');
this i could use in chart.js to build a pie chart.
Thanks guys. Now i can sleep.
$markers =array();
$getmap = $mysqli->query("SELECT `desc`,`lat`,`long` FROM map");
$i=0;
$markers = $getmap->fetch_all(MYSQLI_ASSOC);
echo $markers[1]["desc"];
echo $markers;
$markers = json_encode($markers);
How is it possible such that these will flow properly and it will be read by the JS?
var position = (markers[i][lat], markers[i][long]);
Please try this way:
Hopefully it will help:
foreach($markers as $i=>$arrMarkes)
{
$finalArray[$i] = $arrMarkes;
}
echo json_encode($finalArray);
I'm quite new to php and don't actually know if this is possible
Im currently outputting JSON code with php using the following code
echo json_encode($output, JSON_NUMERIC_CHECK);
But what I want to do is have the above data inside a variable.
I tried
$JSONDATAX = json_encode($output, JSON_NUMERIC_CHECK);
But it doesn't seem to like it when I call $JSONDATAX.
The original echo way works completely fine.
edit ........
$lrs = CDB::ExecuteQuery($sql);
if($lrs) {
$jsonData = convert($lrs);
}
function convert($lrs) {
$intermediate = array();
while ($vals = CDB::GetAssoc($lrs)) {
$key = $vals['POS'];
$x = $vals['CODE'];
$y = $vals['COUNT'];
$intermediate[$key][] = array('x' => $x, 'y' => $y);
}
$output = array();
foreach($intermediate as $key => $values) {
$output[] = array(
"key" => $key,
'values' => $values
);
}
$data1 = json_encode($output, JSON_NUMERIC_CHECK);
}
?>
<script>
var negative_test_data = <?php echo $data1; ?>;
var chart;
nv.addGraph(function() {
chart = nv.models.multiBarChart()
.color(d3.scale.category10().range())
.rotateLabels(0) //Angle to rotate x-axis labels.
.transitionDuration(300)
.showControls(true) //Allow user to switch between 'Grouped' and 'Stacked' mode.
.groupSpacing(0.24) //Distance between each group of bars.
;
As you can see, I am using php just after var negative_test_data , but it doesn't produce anything.
In your edited example, $data is a local variable inside the convert function, so it cannot be accessed outside that function. the result of json_encode should be returned:
$data1 = json_encode($output, JSON_NUMERIC_CHECK);
should be
return json_encode($output, JSON_NUMERIC_CHECK);
Then, the result of the convert function can be echoed:
var negative_test_data = <?php echo $data1; ?>;
should be
var negative_test_data = <?php echo convert($lrs); ?>;
(There should probably be a an additional if around that whole part, depending on what you want to happen when $lrs does not evaluate to true)
This should be all you really need:
$phpvar = json_encode($output);
echo "<script>var negative_test_data = {$phpvar};</script>";
Afternoon all. The code below works perfectly, however, I need to pull each row of the php sql array out and into the script var. Any ideas on how to write a while loop that could do this? Thanks for any help
var enableDays = ["<?php echo mysql_result($result, 0, 'date'); ?>"];
enableDays.push("<?php echo mysql_result($result, 1, 'date'); ?>");
Additional Code::
$rows = array();
while ($row = mysql_fetch_assoc($result))
{
$rows[] = $row;
}
var enableDays = [<?php echo json_encode($rows); ?>];
console.log(enableDays[1]);
You can get the rows using mysqli_fetch_assoc and then encode it to JSON:
<?php
$rows = array();
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
?>
var enableDays = <?php echo json_encode($rows); ?>;
Pull your data out into a PHP array, then transfer that to JavaScript with
var enableDays = <?php echo json_encode($enableDays); ?>;
As an aside, the obligatory recommendation that you should stop using the PHP mysql extension immediately because it is not very safe and has been deprecated; switch to something better (mysqli and PDO are both good choices).
This can't work. Once the page is loaded, all the PHP has run already. But if you're really just adding the next mysql_result for each push, you could have PHP create the entire enableDays array for you:
<?php
echo 'var enableDays = ["' . mysql_result(...) . '", "' . mysql_result(...) . '"];'
?>
Hope this would help
<?php
$res = mysql_fetch_assoc($result)
foreach($res as $key => $val){ ?>
enableDays.push('<?php echo $val; ?>');
<?php }
?>
I'm working on passing 2 fields of SQL through php to javascript. I have read many tutorials on how to create a multidimensional javascript array. Where I get confused is how to code from php to javascript. I have seen a couple of tutorials on how to get the php data to javascript, but none on how to do this with 2 dimensions.
My first hangup is that if I'm creating a multidimensional array I need to count the number of records in my sql data before I declare the java array right?
update:
I got the data to JSON format as suggested below. Is there a way for me to get all of the contents printed to the web page so that I can see them and then narrow down what is displayed?
update III:
code:
mysql_connect("localhost", "bikemap", "pedalhard") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$data = mysql_query("SELECT * FROM gpsdata");
$new_row = array();
$new_column = array();
while($info = mysql_fetch_array($data)){
foreach( $info as $row_num => $row)
{
$thisItem = $row;
$new_row[] = $thisItem;
}
array_push($new_column = $new_row);
}
$json = json_encode($new_column);
echo $json;
?>
Working code:
$data = mysql_query("SELECT * FROM gpsdata");
$aData = array();
while($row = mysql_fetch_assoc($data))
$aData[$row['idgpsdata']] = array($row['userID'],$row['date'],$row['lat'], $row['longi'], $row['alt']);
$json = json_encode($aData);
echo $json;
Fill a PHP array first, it's easier than building the string for a javascript array. Then - as ThiefMaster said as comment - use JSON to make the javascript array.
In PHP, you can use JSON PECL extension
<?php
$arr = array( 1=>array(3,4),
2=>array(4,5));
$json = json_encode($arr);
echo $json;
?>
Output
{"1":[3,4],"2":[4,5]}
In Javascript
var obj = JSON.parse('{"1":[3,4],"2":[4,5]}');
for(var i in obj){
for(var j in obj[i]) {
console.log(obj[i][j]);
}
}
JSON.Parse is for Gecko (Firefox alike), for cross-browser javascript JSON parse check jQuery.parseJSON or https://stackoverflow.com/search?q=json+parse+javascript
Sample implementation in PHP/jQuery, would be something like this:
json.php
$arr = array( 1=>array('Name', 'Age'),
2=>array('Fares','18'));
$json = json_encode($arr);
echo $json;
json.html
<html><head></head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script>
$.getJSON('json.php', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
</script>
</body>
</html>