I have an object array var codropsEvents={[date1]:['event1'],[date2]:['event2'};
I want to insert multiple values to event1 i.e {[date1]:['event1','event2'],..}
I use the following code
<?php
$da=[];
$qry="select * from events";
$ex=mysqli_query($con,$qry);
while($row=mysqli_fetch_assoc($ex))
{
$timestamp = strtotime($row['date']);
$date= date('m-d-Y', $timestamp);
$event=$row['event'];
$da[]=$date;
$eve[]=$event;
}
?>
<script type="text/javascript">
var a=<?php echo(json_encode($da)); ?>;
var ev= <?php echo(json_encode($eve)); ?>;
var codropsEvents ={};
for(var i=0;i<a.length;i++)
{
codropsEvents[a[i]] = '<span>'+[ev[i]]+'</span>';
}
</script>
But using this code I got something like this,
var codropsEvents={[date1]:[event1],[date1]:[event2]}
But I need all events with same date in a single key is {[date1]:['event1','event2',..],[date2]:[''event3','event4'..],..};
Please anyone can help me
You need to check whether the key exists in the object, if not initialize it with empty array. Then push elements into the array.
<script type="text/javascript">
var a=<?php echo(json_encode($da)); ?>;
var ev= <?php echo(json_encode($eve)); ?>;
var codropsEvents ={};
for(var i=0;i<a.length;i++)
{
if (!codropsEvents[a[i]]) {
codropsEvents[a[i]] = [];
}
codropsEvents[a[i]].push('<span>'+[ev[i]]+'</span>');
}
</script>
Related
hei,
$i=0;
while($row = $result->fetch_assoc()) {
echo "
<tr><td>".$row["Number"]."</td><td>".$row["MusikName"]." ".$row["MusikURL"]."</td></tr>";
this part works...it give me -> 1 test1 url1.de 2 test2 url2.de ...
So what I want is to pass the URL to a JavaScript Array...by doing in phpscript
$urlarray[]=$row["MusikURL"];
echo $urlarray[$i]; // gives me url1.de url2.de url3.de
i++; // to fill $urlarray[1] [2] [...] with urls
How do I pass the urls to a JavaScript Array so that I can access to those by
javascriptarrayurl[1] javascriptarrayurl[2] (result should be a clear url) ... I got troubles with JSON :c
thanks in advance !!
You can use jQuery and have something like
<?php
$returnArray = array();
while ($row = $result->fetch_assoc()) {
array_push($returnArray, $row);
}
$jsonArray = json_encode($returnArray);
?>
<script>
$(document).ready(function () {
var objArray = $.parseJSON("<?php echo $jsonArray; ?>");
for (var i = 0; i < objArray.length; i++) {
var row = objArray[i];
console.log(row);
// Now here you have access to row.Number row.MusikURL
}
});
You can use json_encode() to convert a PHP variable to its Javascript literal notation.
<script>
var urlarray = <?php echo json_encode($urlarray); ?>;
</script>
Here's what I got
$x=$ris;
while ($x<$rie){
array_push($array, pg_fetch_result($result,$x,0));
$x=$x+1;
}
So I'm just pushing lot's of values from a column to $array. I want to transmit the data in this array to a js array. So here's what's happening:
<script>
var temp = <?php echo json_encode($rie-$ris); ?>;
var temp2=0;
var jarray = [];
while (temp2<temp)
{
jarray.push(<?php echo json_encode($array[temp2]); ?>);
temp2++;
}
console.log(jarray)
</script>
Whenever I try to print anything out, jarray has nothing in it, which leads me to think that this
jarray.push(<?php echo json_encode($array[temp2]); ?>);
line is messed up. It's probably because I'm trying to reference a js variable in a php echo. The problem is I'm trying to make a while loop to just copy the array over, but in js, I'm incrementing a js var, so how can I possibly do this?
Try my code. First json_encode your php array and then JSON.parse in js after that while loop.
<script>
var temp = <?php echo json_encode($rie-$ris); ?>;
var temp2=0;
var jarray = [];
var arr = '<?php echo json_encode($array); ?>';
var arr_p = JSON.parse(arr);
while (temp2<temp)
{
jarray.push(arr_p[temp2]);
temp2++;
}
console.log(jarray)
</script>
I was making an image gallery with up and down buttons ,the array $imageids contains all image ids. I want to access these values with
JavaScript as follows,
PHP :
require"./connect.php";
$imgquery = mysql_query("SELECT * FROM press INNER JOIN subscriptions ON press.userid=subscriptions.to_u WHERE subscriptions.from_u='30' ORDER BY press.id DESC ");
$countrow = mysql_num_rows($imgquery);
$imageids = array();
while($fimgq = mysql_fetch_assoc($imgq)) {
$imgid = $fimgq['id'];
array_push($imageids,$imgid);
}
JavaScript:
$(document).ready(function() {
var i = -1;
var cr = <?php echo $countrow ?>;
$('#down').click(function() {
if (i < cr-1) {
i = i + 1;
var ard = <?php echo $imageids[i]?>;
alert(ard);
}
});
$('#up').click(function() {
if(i>0) {
i = i - 1;
var aru = <?php echo $imageids[i]?>;
alert(aru);
}
});
});
I want to get $imageids elements by putting a javascript variable i inside $imageids[] array , like
var ard = <?php echo $imageids[i]?>;
alert(ard); // Which doesn't work
As #chris85 and #Khalos pointed out in comments, the PHP variables are all dead once the JavaScript runs, so you need to output all the ID:s into an JavaScript array. It would looke something like this:
$(document).ready(function(){
var i=-1;
var cr= <?php echo $countrow ?>;
//Save all the ID:s to a JS variable so they can be used later.
var imageids = [<?php echo implode(',', $imageids); ?>];
$('#down').click(function(){
if(i<cr-1) {
i=i+1;
alert(imageids[i]); //This uses the JS variable imageids, not the dead PHP one.
}
});
$('#up').click(function(){
if(i>0) {
i=i-1;
alert(imageids[i]); //Same as above.
}
});
});
Right now I am using a manually inputted array of dates called disable to disable dates in the jquery UI datepicker with the beforeShowDay method. This is working fine, however, I have a php variable $disablethese which is storing a dynamic array of dates to disable. For some reason, I can't seem to convert my php array into a javascript array (which I'm calling unavailabledates). It doesn't throw any errors but it just doesn't work block out the dates the same way as the static array.
<script type="text/javascript">
var unavailabledates = <?php echo json_encode($disablethese); ?>;
</script>
<script src="js/datepicker-admin.js"></script>
Here is datepicker-admin.js
$(document).ready(function() {
var disable = ["2014-01-03","2014-01-13","2014-01-23"];
$('#fromDate').datepicker({
beforeShowDay: function(date) {
if($.inArray($.datepicker.formatDate('yy-mm-dd', date ), disable) > -1) {
return [false, "highlighted", "Booked out"];
} else {
return [true, "", "available"];
}
}
});
});
you can use $.parseJSON function.
<script type="text/javascript">
var unavailabledates = $.parseJSON('<?php echo json_encode($disablethese); ?>');
</script>
<script src="js/datepicker-admin.js"></script>
You can use .push to insert all values to an array.
<script type="text/javascript">
var unavailabledates = new Array();
<?php
$disbaleddates = json_encode($disablethese);
for($i=0;$i<count($disbaleddates);$i++) { ?>;
unavailabledates.push('<?=$disbaleddates[$i]?>');
<?php } ?>
</script>
<script src="js/datepicker-admin.js"></script>
This may solve your problem, But it's might have a long way!! :)
You can use directly JSON.parse()
var unavailabledates = JSON.parse(<?php echo json_encode($disablethese); ?>);
1) Create a hidden field in php page:
<input id="disable-dates" type="hidden" value="<?php echo json_encode($disablethese); ?>">
2)
Use jquery :
<script type="text/javascript">
var unavailabledates = $.parseJSON($('#disable-dates').val());
</script>
Both simulatneously
Did you assign your unavailabledates in
var disable = ["2014-01-03","2014-01-13","2014-01-23"];
like
var disable = unavailabledates;
I'm using laravel and this works beautifully:
var something = JSON.parse('{!! json_encode(['foo' => 'bar']) !!}');
I was very confused for a little bit cause I couldn't figure out why this DOES NOT work:
var something = JSON.parse('{{ json_encode(['foo' => 'bar']) }}');
the second way escapes HTML entities in the document. but yea, that's only with laravel.
var obj = <?php echo json_encode($_GET) ?>;
I have a php array and I want to add its value to a javascript array. For example I am doing it something like this.
$k_data = json_encode($k)
Thus
k_data = [2,3,4,8,9]
Now in javascript I am doing like the following
var s4 = [[]];
for(var i = 0; i<5; i++)
{
s4.push([i,$k_data[i]]);
}
plot5.series[0].data = s4;
where plot5 is jqplot graph. But this is not working, I am getting blank graph while the following thing is working
for(var i = 0; i<5; i++)
{
s4.push([i,Math.sin(i)]);
}
Where I am making mistake?
If you want to deal with the php array only, you can do this-
First, implode the array to make a comma-separated string, say $str. Just like-
<?php
$str = implode(",", $array);
?>
Then, use split to convert the php string to the javascript array. Just like-
<script>
var str = <?php echo $str; ?>;
var array = str.split(',');
</script>
OR, json_encode() can help you directly-
<script>
<?php
$js_array = json_encode($php_array);
echo "var js_array = ". $js_array . ";\n";
?>
</script>
Well you can do a for loop and echo the Javascript commands to fill the Javascript Array
<script>
var s4 = [[]];
<?php
$k_data = json_encode($k)
$i = 0;
foreach($k_data as $v) {
echo 's4.push([' , $i , ',Math.sin(' , $v , ')]);';
++$i;
}
?>
plot5.series[0].data = s4;
</script>
It seems that you are refering to a php variable in you javascript. Keep in mind that PHP is executed serverside, whereas javascript is executed by the browser. Therefore, you need to pass the PHP variable to your javascript. Assuming that your javascript and PHP are in one .php file, replacing above javascript with the following should work:
<?php $k_data_js = implode("','", $k_data); ?>
var k_data = <?php echo "['" . $k_data_js . "']"; ?>;
var s4 = [[]];
for(var i = 0; i<k_data.length; i++)
{
s4.push([i,k_data[i]]);
}
plot5.series[0].data = s4;
The variable is passed to javascript in the second line. From then on you can refer to k_data in your script.