How to integrate PHP with javascript variables? - javascript

I want to do something like this:
for (var i = 0; i < massages.length; i++)
{
commentBoxDiv.appendChild(createCommentBox("<?php echo $massages[i]['likes']; ?> people like this.", i));
}
but I don't know how to break the syntax in order to access the i variable.

With a little json_encode and some creativity, you can work out a solution like the following:
<script>
var messages = <?php echo json_encode($messages); ?>;
for(var i = 0; i < messages.length; i++) {
commentBoxDiv.appendChild(createCommentBox(messages[i].likes + " %d people like this.", i));
}
</script>

You can't use JS variables inside php code block. You must iterate $massages array and make from them JS objects.

Related

Passing array data from php to javascript using a loop

Is there a similar way to implement this kind of "algorithm" in the right way?
for(i=0;i<howManyCourses;i++){
var stored = "<?php echo $buf[i] ?>";
var option = document.createElement("option");
option.text=stored;
e.add(option);
}
So I want to pass the data from the $buf array into a javascript variable. I've tried many ways but it seems like I cannot find the solution. I'm new into php and I apologise for any obvious mistake.
It should be in the same file or in another case AJAX will be the solution.
<script type="text/javascript">
const arr = <?php echo json_encode($buf); ?>;
for (var i = 0; i < arr.length ; i++) {
//do something
}
</script>
If you need that JS' variable buf contain the same elements as PHP's $buf, you can do the following:
var buf = <?php echo json_encode($buf); ?>;
Just keep in mind that if PHP's $buf is not an indexed array, JS' buf will be an object instead of an array.

Get Javascript variable as an index with PHP array in Javascript

Want javascript variable as index variable in php array in javascript.
Code is not working .....
<script>
var total = <?php echo count($resvalue); ?> ; //$resvalue is an array holding the values are 1,2,3,4. total will hold count of that array.
for(var j=0;j<total;j++)
{
<php echo $resvalue[j]; ?> // where j is javascript variable and $resvalue is PHP array
}
</script>
You cannot read values in a php array from javascript. Instead echo the array and turn it into a javascript array and let javascript do the count.
<script>
var resvalue = [<?php echo $resvalue; ?>]; // or something like this
for(var j=0; j < resvalue.length; j++)
{
// your value is available in the js-array
// resvalue[j]
}
</script>

Pass variables and data from PHP to JavaScript?

This is not a duplicate of How to pass variables and data from PHP to JavaScript?
After consulting the previous question, I have another :
My problem is that when I get the php array in Js, and I print it, I have just [object][object]
<?php
$tl = array(
0=>array('a', 'b', 1),
1=>array('c', 'd', 2)
);
?>
and javascript :
<script type="text/javascript">
var arr= <?php echo json_encode($tl ); ?>;
for(var i=0;i<3;i++){
alert(arr[i]);
}
</script>
You should display it using console.log instead of alert :
console.log(arr[i]); //Check the result in you browser console
console.log : Formats your objects nicely and allows to traverse them.
Hope this helps.
Remember:
You don't have more than 2 object in your array so you should not run loop more than 2 times.
first loop give you permission to access the object of array then you can run a loop to show/get the property of object.
<?php
$tl = array(
0=>array('a', 'b', 1),
1=>array('c', 'd', 2)
);
?>
var arr = ;
for(var i=0;i<2;i++){
for(var j=0;j<3;j++){
alert(arr[i][j]);
console.log(arr[i][j]);// you can also show the value from the console of your browser
}
}
output of console
Try this ;)
alert() shows type if not basic data type. In your case it's Object that's why it's showing [object][object]
To debug JavaScript one should use console.log() and other console methods like:
console.log();
console.debug();
console.warn();
console.error();
etc.
One more thing here you are trying to access values of nested array so you can go with alert like this:
var arr= <?php echo json_encode($tl ); ?>;
for(var i=0;i<3;i++){
alert(arr[i][0] + " " + arr[i][1] + " " + arr[i][2]);
}
OR
Use nested loop to iterate inner array values;
try this:
<input type="hidden" id="array" value="<?php echo json_encode($tl); ?>" />
then use
<script type="text/javascript">
var arr = getElementById('array').value
for(var i=0;i<3;i++){
alert(arr[i]);
}
</script>

For loop issue - javascript - php - google maps

I'm using this for loop in javascript and I'm trying to create polygons on a google map with data retrieved from database. my problem here is that i have included php inside the javascript and each time the for loop runs the value of $i is never changed. anyone can help??
enter code here
<?php $i = 0 ?>;
for(i =0; i< <?=$length?>; i++)
{
var coordinates = "<?=$districtsarray[$i]['coords']?>";
var coordinates = coordinates.substr(1, coordinates.length-2).split("),(");
var souniCoordinates = coordinates.map(function(pointString){
var latlon = pointString.split(", ");
return new google.maps.LatLng(latlon[0], latlon[1]);
});
var SouniCoords = [souniCoordinates];
<?php echo $districtsarray[$i]['name']?> = new google.maps.Polygon({
paths: SouniCoords,
strokeColor: '#383838 ',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#CD5C5C ',
fillOpacity: 0.5
});
<?php echo $districtsarray[$i]['name']?>.setMap(map);
<?php $i=$i+1;?>
}
</script>
<?php
In my opinion mixing PHP and JavaScript like this makes code hard to read and maintain. I would recommend using the PHP function json_encode (http://php.net/manual/en/function.json-encode.php) to convert your PHP data structure into JSON and echo it out in one place.
Then use JSON.parse() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse to convert the string into a JavaScript object.
So it might look something like this:
var data = JSON.parse(<?php echo json_encode($data); ?>);
Then only use JavaScript after this point :).
step 1) take value of php variable into a javascript variable like this
var javascriptarray = JSON.parse('< json_encode($districtsarray); ?>');
step 2) now use "javascriptarray" & javascript variable "i" in loop to access its elements like this
var coordinates = javascriptarray[i]['coords'];
Firstly, please understand that the above is bad practice as it makes maintenance/debugging somewhere between awkward and impossible. If you are insistent on doing so, a better alternative would be to use string interpolation:
<?php
echo <<< END
//always use K&R style for js because of automatic ; insertion:
for (var i=0, i < $length, i++) {
//do stuff
}
END
?>
The way you have written it 'i' has no definition in javascript, incrementing undefined does not have a meaningful result. Because of these kinds of problems you should not mix javascript and php like this. A better alternative is:
$.getJSON('myPHP.php', function(response) {
var data = JSON.parse(response);
for (index in data) {
var row = data[index]
//do stuff
}
})
This uses jquery although it is certainly possible to achieve this with raw js, it just takes more code. Have the php script 'myPHP' return an array with the records from the db.

How can i generate new name in the loop?

Here is my Code:
for($i=0;$i<10;$i++)
{
$elem=data;
}
Here need instead $elem get $elem1, $elem2, $elem3 depending on the $i.
Example:
If $i = 1 row $elem=data should been $elem1=data
If $i = 2 row $elem=data should been $elem1=data
$('#div1').html($elem1);
$('#div2').html($elem2);
$('#div3').html($elem3);
Tell me please how make this?
P.S.: if you do not get the idea you can ask questions
Based on your sample snippets, this code fits your purpose just fine.
var data = [1,2,3,4,5];
for(var i=0;i < data.length; i++)
{
var elem = data[i];
// other data manipulations
$('#div'+(i+1)).html(elem);
}
http://jsfiddle.net/LmvAb/
As it is JavaScript you can do what you want. Please don't ever use this over an array unless you absolutely need to. You need to use the eval() function.
$data = "worked";
for(var $i=0;$i<10;$i++){
eval('$elem' + $i + '= $data');
}
alert(eval('$elem1'));
alert(eval('$elem2'));
alert(eval('$elem5'));
JSFiddle: http://jsfiddle.net/begWG/1/

Categories

Resources