Im trying to update the src from the audio tag if i click on a button.
So i need to translate the $muziek variable to Jquery
View:
<?php
foreach ($muziek as $ms)
{
if ($ms->id == 2) {
echo '<audio id="player" controls src="data:audio/mpeg;base64,' . base64_encode($ms->audio) . '">';
echo '</audio>';
}
}
foreach ($muziek as $ms)
{
echo '<br>';
echo '<input id="'.$ms->id.'" type="button" value="' . $ms->naam . '" class = "btn btn-login login-formcontrol"/>';
}
?>
</div>
<script>
$("input").click(function () {
var test = $(this).attr("id");
console.log(test);
//Here needs to be the foreach muziek
});
</script>
Muziek variable:
This is how i fill the music variable
function getAllMuziek()
{
$query = $this->db->get('muziek');
$muziek = $query->result();
return $muziek;
}
Does someone has an idea or show me how this can be done?
I spent sometime trying to figure out what you want and from what i understood you want to return an array of all muzieks returned to your js to do whatever you wanna do with it, which you can simply get with a simple ajax request:
$.get( "base_url/your_controller/getAllMuziek" )
.done(function( muziek ) {
//Here needs to be the foreach muziek
$.each(muziek, function( index, value ) {
// whatever
});
});
with a simple modification to your method getAllMuziek:
function getAllMuziek()
{
$query = $this->db->get('muziek');
$muziek = $query->result();
header('Content-Type: application/json');
echo json_encode($muziek);
}
now when you make you ajax call you will get your result.
Convert $muziek into javascript array using json_encode
<script>
var myArray = <?php echo json_encode($muziek); ?>;
</script>
Hey just a small thing I am stuck on.
I do have the structure ready for the JS array but I need to assign it to a variable like
var data ={ Php array }
Here is the structure of my php array: https://imgur.com/a/LPbCqEu This is just a part of the array.
My code looks like this:
$csvfile = 'Property_CSVTruncated.csv';
$handle = fopen($csvfile, 'r');
$jsData = array(
'properties' =>array()
);
$header = NULL;
while (($row = fgetcsv($handle, 1000000, ',')) !== FALSE) {
$i = 0;
if (!$header) {
$header = $row;
} else {
$data = array_combine($header, $row);
$fields = array(
'_id' => $data['C4021040'],
'index' => $i,
'price' => $data['123'],
'picture' => "https://ihatetomatoes.net/demos/_rw/01-real-estate/tn_property01.jpg",
'city' => "Calgary",
'MLS# ' => $data['C4021040'],
'address' => $data['6 ASPEN RIDGE LN SW'],
'latitude' => $data['51.045681'],
'longitude' => $data['-114.191544'],
'Bed' => $data['123'],
'Bath' => $data['123'],
'capSpaces' => $data['T3H 5H9'],
);
array_push($jsData['properties'], $fields);
}
$i++;
}
fclose($handle);
$str = "const data = ";
print($str);
header('Content-type: application/json');
json_encode($jsData, JSON_NUMERIC_CHECK);
$jsonFile = fopen('csvTojs.js', 'w');
fwrite($jsonFile, json_encode($jsData));
fclose($jsonFile);
So basically I need that string 'var data = ' and then prints the array.
Anyway to do that in php itself?
Thanks
in server, echo json_encode($phpArray) and exit;
in callback of ajax or init js variable, parse json to array with JSON.parse('jsonString');
Use json_encode()
<script>
var data = <?php echo json_encode($jsData, JSON_PRETTY_PRINT); ?>
</script>
Or in your case:
header('Content-Type: application/json');
echo json_encode($jsData);
exit;
I can't get it to work despite all the sources. I try the following :
<?php
$list_array = array();
foreach ($this->resultatTypeMail as $mailType) {
$nom = $mailType->getNom();
$objet = $mailType->getObjet();
$list_array[] = array(
'Name' => $nom,
'Object' => $objet,
);
echo "<script type='text/javascript'>alert('$nom');</script>"; // this is OK
echo "<script type='text/javascript'>alert('$objet');</script>"; // this is OK
}
?>
<script type="text/javascript">
var js_array = [<?php echo json_encode( $list_array ); ?>];
alert(js_array[0]); // This returns undefined
</script>
I get satisfying results on $nom and $objet when I alert them.
Problem :
js_array[0] returns undefined
Note that I'm not in UTF-8. I'm not sure it's relevant though.
EDIT : A big picture of my goal is to get an array of custom php objet to be usable in JS.
Just remove the [] from var js_array = line and it will work:
wrong:
var js_array = [<?php echo json_encode( array_values($list_array) ); ?>];
right:
var js_array = <?php echo json_encode( array_values($list_array) ); ?>;
Working code:
<?php
class MailType {
function __construct($n, $o) {
$this->nom = $n;
$this->objet = $o;
}
private $nom;
private $objet;
public function getNom() {
return $this->nom;
}
public function getObjet() {
return $this->objet;
}
}
$list_array = array();
$resultatTypeMail = array(new MailType('John', 'obj1'), new MailType('Mary', 'obj2'));
foreach ($resultatTypeMail as $mailType) {
$nom = $mailType->getNom();
$objet = $mailType->getObjet();
$list_array[] = array(
'Name' => $nom,
'Object' => $objet,
);
//echo "<script type='text/javascript'>alert('$nom');</script>"; // this is OK
//echo "<script type='text/javascript'>alert('$objet');</script>"; // this is OK
}
?>
<script type="text/javascript">
var js_array = <?php echo json_encode( $list_array ) ?>;
alert(js_array[0].Name); // This returns John
</script>
You can see it running here: http://phpfiddle.org/main/code/5xei-ybpn
(press F9 or click on 'Run - F9' to Run)
In PHP an array that has string keys gets converted to an object when parsed with json_encode.
You could either use array_keys to force the creation of an array, or use the object notation in your javascript
<?php
$list_array = array();
foreach ($this->resultatTypeMail as $mailType) {
$nom = $mailType->getNom();
$objet = $mailType->getObjet();
$list_array[] = array(
'Name' => $nom,
'Object' => $objet,
);
echo "<script type='text/javascript'>alert('$nom');</script>"; // this is OK
echo "<script type='text/javascript'>alert('$objet');</script>"; // this is OK
}
<script type="text/javascript">
var js_array = [<?php echo json_encode( array_values($list_array) ); ?>];
alert(js_array[0]);
</script>
Or
<?php
$list_array = array();
foreach ($this->resultatTypeMail as $mailType) {
$nom = $mailType->getNom();
$objet = $mailType->getObjet();
$list_array[] = array(
'Name' => $nom,
'Object' => $objet,
);
echo "<script type='text/javascript'>alert('$nom');</script>"; // this is OK
echo "<script type='text/javascript'>alert('$objet');</script>"; // this is OK
}
<script type="text/javascript">
var js_array = [<?php echo json_encode( array_values($list_array) ); ?>];
alert(js_array.Name);
</script>
I think you have multiple issues: you're missing the ; after the json_encode() line (which is not actually required); you're surrounding the result of json_encode() with brackets (which should work but I expect it's not what you want); and the most important, you're missing the closing PHP ?> tag before printing the JS...
This works for me:
<?php
// your PHP code here...
?>
<script type="text/javascript">
var js_array = <?php echo json_encode($list_array); ?>;
alert(js_array[0]); // This works for me!
</script>
It looks like the issue may be in the encoding as you say - it seems that json_encode only works with UTF-8! From the json_encode() docs:
All string data must be UTF-8 encoded.
So I think you'll have to convert your strings to UTF-8 before putting them into the array, something like:
$list_array[] = array(
'Name' => utf8_encode($nom),
'Object' => utf8_encode($objet),
);
I think just that should work - otherwise you can try this from the comments in the same json_encode() docs; or this other question to get more ideas...
I am creating a Javascript array during dom creation using arr.push.
However, on page ready function, it returns an empty array.
<script type="text/javascript">
var short_urls = [];
</script>
$(document).ready(function() {
console.log(short_urls);
});
<?
foreach ($d_json['result'] as $key => $value) {
?>
<script>
short_urls.push("<? echo $shorten_url ?>");
</script>
<?
}
?>
<script type="text/javascript">
var short_urls = [];
$(document).ready(function() {
console.log(short_urls);
});
</script>
<?
foreach ($d_json['result'] as $key => $value) {
?>
<script>
short_urls.push("<? echo $shorten_url ?>");
</script>
<?
}
?>
As PHP will be executed before any javascript you can write the javascript variables out without needing to use the array.push method. However, the question used a php variable $shorten_url - where is that defined? I assume it is the value from the foreach loop
Approach #1
-----------
<script type="text/javascript">
var short_urls = [];
<?php
foreach( $d_json['result'] as $key => $value ) {
$shorten_url='???';
echo "short_urls.push('{$shorten_url}');";
}
?>
$( document).ready( function() { console.log( short_urls ); } );
</script>
Approach #2
-----------
<script type="text/javascript">
<?php
$tmp=array();
foreach( $d_json['result'] as $key => $value ) {
$shorten_url='???';
$tmp[]=$shorten_url;
}
echo "var short_urls = ['".implode("','",$tmp)."'];";
?>
$( document).ready( function() { console.log( short_urls ); } );
</script>
i want to get the json format from my SQL database using PHP
here is a capture of mySql database
data.php
<?php include("include/connexion.php");
$requete = "SELECT * from statistika";
$resultat = mysql_query( $requete ) or die( mysql_error() );
$rows = array();
$total_vue = 0;
here is the php code to get the data
while( $data = mysql_fetch_assoc( $resultat ) ) {
$total_vue+=$data['temps'];
$rows[] = array(
"date" => strtotime( $data['date']) * 1000,
"value" => $data[ 'temps' ]
);
}
?>
json_encode.php
<?php
include("data.php");
echo json_encode($rows);
?>
The content of json_encode is valid and i get the json format successfully
[{"date":1439769600000,"value":"5"},{"date":1439787600000,"value":"12"},{"date":1439806631000,"value":"8"},{"date":1439821320000,"value":"18"},{"date":1439919642000,"value":"6"},{"date":1439889752000,"value":"2"},{"date":1439893260000,"value":"20"},{"date":1439906400000,"value":"9"},{"date":1429308000000,"value":"15"},{"date":1421535600000,"value":"12"},{"date":1413583200000,"value":"18"},{"date":1405634400000,"value":"6"},{"date":1439828640000,"value":"14"},{"date":1439935200000,"value":"19"},{"date":1439863200000,"value":"12"},{"date":1439884800000,"value":"18"},{"date":1439917200000,"value":"26"},{"date":1439920800000,"value":"4"},{"date":1439904320000,"value":"0"},{"date":1439907420000,"value":"1"},{"date":1439907428000,"value":"1"},{"date":1439907434000,"value":"3"},{"date":1439907437000,"value":"1"},{"date":1439907447000,"value":"8"},{"date":1439907452000,"value":"3"},{"date":1439907459000,"value":"5"},{"date":1439907469000,"value":"8"},{"date":1439907482000,"value":"10"},{"date":1439907507000,"value":"21"},{"date":1439907510000,"value":"1"},{"date":1439907519000,"value":"7"},{"date":1439907526000,"value":"5"},{"date":1439907547000,"value":"18"},{"date":1439907557000,"value":"8"},{"date":1439907560000,"value":"1"},{"date":1439907576000,"value":"3"},{"date":1439907581000,"value":"3"},{"date":1418857200000,"value":"300"},{"date":1426633200000,"value":"450"},{"date":1434578400000,"value":"500"},{"date":1424214000000,"value":"600"}]
Now i want to pass the JSON format to javascript , i am using this code
var foo = {};
foo.toString = function () { return <?php echo json_encode($rows);?> };
document.write(foo.toString);
the problem is that when printing foo.toString i get this
function () { return [{"date":1439769600000,"value":"5"},{"date":1439787600000,"value":"12"},{"date":1439806631000,"value":"8"},{"date":1439821320000,"value":"18"},{"date":1439919642000,"value":"6"},{"date":1439889752000,"value":"2"},{"date":1439893260000,"value":"20"},{"date":1439906400000,"value":"9"},{"date":1429308000000,"value":"15"},{"date":1421535600000,"value":"12"},{"date":1413583200000,"value":"18"},{"date":1405634400000,"value":"6"},{"date":1439828640000,"value":"14"},{"date":1439935200000,"value":"19"},{"date":1439863200000,"value":"12"},{"date":1439884800000,"value":"18"},{"date":1439917200000,"value":"26"},{"date":1439920800000,"value":"4"},{"date":1439904320000,"value":"0"},{"date":1439907420000,"value":"1"},{"date":1439907428000,"value":"1"},{"date":1439907434000,"value":"3"},{"date":1439907437000,"value":"1"},{"date":1439907447000,"value":"8"},{"date":1439907452000,"value":"3"},{"date":1439907459000,"value":"5"},{"date":1439907469000,"value":"8"},{"date":1439907482000,"value":"10"},{"date":1439907507000,"value":"21"},{"date":1439907510000,"value":"1"},{"date":1439907519000,"value":"7"},{"date":1439907526000,"value":"5"},{"date":1439907547000,"value":"18"},{"date":1439907557000,"value":"8"},{"date":1439907560000,"value":"1"},{"date":1439907576000,"value":"3"},{"date":1439907581000,"value":"3"},{"date":1418857200000,"value":"300"},{"date":1426633200000,"value":"450"},{"date":1434578400000,"value":"500"},{"date":1424214000000,"value":"600"}]
i don't want function () { return to appear in the output !!!
Any hints ?
thanks .
Change this line in your JS code
From
foo.toString = function () { return <?php echo json_encode($rows);?> };
To
foo.toString = '<?php echo json_encode($rows);?>';
var foo = {};
foo.toString = function () { return <?php echo json_encode($rows);?> };
document.write(foo());
You are creating foo as function so call like this you will get only json.