Get Javascript variable as an index with PHP array in Javascript - 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>

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.

Accessing parts of a php array in a javascript for loop

I'm trying to access and display elements of a php array in a javascript for loop, whenever I try and log out a value it always returns blank and I can't figure out why.
for(let i=0;i<"<?php echo sizeof($response['results']); ?>"; i++) {
console.log(i);
let divElement = document.createElement("div");
divElement.className = "col col-6 col-md-4 col-lg-3";
let h4Name=document.createElement('h4');
h4Name.className="name";
h4Name.innerHTML="<?php echo $response['results'][i]['name']?>;"
console.log("<?php echo $response['results'][i]['name']?>");
divElement.appendChild(h4Name);
let h4Address=document.createElement('h4');
h4Address.className="address";
h4Address.innerHTML="<?php echo $response['results'][i]['formatted_address']?>";
divElement.appendChild(h4Address);
document.querySelector(".row").appendChild(divElement);
}
You can't loop thru a JS array and access a corresponding PHP array. PHP is a back end code and JS (in this case) is a front end code.
One option you have is to have a result variable in javascript and use that array to loop.
Like:
//Put the PHP array into a JS variable
const results = <?php echo json_encode( $response['results'] );?>
//Loop thru the JS variable
for (let i = 0; i < results.length; i++) {
//Access object property as results[i]['formatted_address'] or results[i].formatted_address
//.........
}

How to set php array to html element data attribute as javascript array? [duplicate]

This question already has answers here:
Convert php array to Javascript
(21 answers)
Closed 3 years ago.
I'm trying to convert a PHP array to a javascript array for jQuery's datetimepicker to disable some dates. But I can't seem to find the right answer on the internet. I'm using Zend Framework for my project.
<?php
$ConvertDateBack = Zend_Controller_Action_HelperBroker::getStaticHelper('ConvertDate');
$disabledDaysRange = array();
foreach($this->reservedDates as $dates) {
$date = $ConvertDateBack->ConvertDateBack($dates->reservation_date);
$disabledDaysRange[] = $date;
}
?>
<script>
var disabledDaysRange = $disabledDaysRange ???? Please Help;
$(function() {
function disableRangeOfDays(d) {
for(var i = 0; i < disabledDaysRange.length; i++) {
if($.isArray(disabledDaysRange[i])) {
for(var j = 0; j < disabledDaysRange[i].length; j++) {
var r = disabledDaysRange[i][j].split(" to ");
r[0] = r[0].split("-");
r[1] = r[1].split("-");
if(new Date(r[0][2], (r[0][0]-1), r[0][1]) <= d && d <= new Date(r[1][2], (r[1][0]-1), r[1][1])) {
return [false];
}
}
}else{
if(((d.getMonth()+1) + '-' + d.getDate() + '-' + d.getFullYear()) == disabledDaysRange[i]) {
return [false];
}
}
}
return [true];
}
$('#date').datepicker({
dateFormat: 'dd/mm/yy',
beforeShowDay: disableRangeOfDays
});
});
</script>
To convert you PHP array to JS , you can do it like this :
var js_array = [<?php echo '"'.implode('","', $disabledDaysRange ).'"' ?>];
or using JSON_ENCODE :
var js_array =<?php echo json_encode($disabledDaysRange );?>;
Example without JSON_ENCODE:
<script type='text/javascript'>
<?php
$php_array = array('abc','def','ghi');
?>
var js_array = [<?php echo '"'.implode('","', $php_array).'"' ?>];
alert(js_array[0]);
</script>
Example with JSON_ENCODE :
<script type='text/javascript'>
<?php
$php_array = array('abc','def','ghi');
?>
var js_array =<?php echo json_encode($disabledDaysRange );?>;
alert(js_array[0]);
</script>
The PHP json_encode function translates the data passed to it to a JSON string which can then be output to a JavaScript variable.The PHP json_encode function returns a string containing the JSON equivalent of the value passed to it.
<?php
$ar = array('apple', 'orange', 'banana', 'strawberry');
echo json_encode($ar); // ["apple","orange","banana","strawberry"]
?>
You can pass the JSON string output by json_encode to a JavaScript variable as follows:
<script type="text/javascript">
// pass PHP variable declared above to JavaScript variable
var ar = <?php echo json_encode($ar) ?>;
</script>
A numerically indexed PHP array is translated to an array literal in the JSON string. A JSON_FORCE_OBJECT option can be used if you want the array to be output as an object instead:
<?php
echo json_encode($ar, JSON_FORCE_OBJECT);
// {"0":"apple","1":"orange","2":"banana","3":"strawberry"}
?>
Associative Array Example:
<?php
$book = array(
"title" => "JavaScript: The Definitive Guide",
"author" => "David Flanagan",
"edition" => 6
);
?>
<script type="text/javascript">
var book = <?php echo json_encode($book, JSON_PRETTY_PRINT) ?>;
/* var book = {
"title": "JavaScript: The Definitive Guide",
"author": "David Flanagan",
"edition": 6
}; */
alert(book.title);
</script>
Notice that PHP's associative array becomes an object literal in JavaScript. We use the JSON_PRETTY_PRINT option as the second argument to json_encode to display the output in a readable format.
You can access object properties using dot syntax, as displayed with the alert included above, or square bracket syntax: book['title'].
here you can find more information and details.
When we convert PHP array into JS array then we get all values in string.
For example:
var ars= '<?php echo json_encode($abc); ?>';
The issue in above method is when we try to get the first element of ars[0] then it gives us bracket where as in we need first element as compare to bracket so the better way to this is
var packing_slip_orders = JSON.parse('<?php echo json_encode($packing_slip_orders); ?>');
You should use json_parse after json_encode to get the accurate array result.
Have you tried using json_encode http://php.net/manual/en/function.json-encode.php
It converts an array to a json string
This may be a easy solution.
var mydate = '<?php implode("##",$youdateArray); ?>';
var ret = mydate.split("##");
<?php
$ConvertDateBack = Zend_Controller_Action_HelperBroker::getStaticHelper('ConvertDate');
$disabledDaysRange = array();
foreach($this->reservedDates as $dates) {
$date = $ConvertDateBack->ConvertDateBack($dates->reservation_date);
$disabledDaysRange[] = $date;
}
$disDays = size($disabledDaysRange);
?>
<script>
var disabledDaysRange = {};
var disDays = '<?=$disDays;?>';
for(i=0;i<disDays;i++) {
array.push(disabledDaysRange,'<?=$disabledDaysRange[' + i + '];?>');
}
............................
<script> var disabledDaysRange = $disabledDaysRange ???? Please Help;
$(function() {
function disableRangeOfDays(d) {
in the above assign array to javascript variable "disableDaysRange"
$disallowDates = "";
echo "[";
foreach($disabledDaysRange as $disableDates){
$disallowDates .= "'".$disableDates."',";
}
echo substr(disallowDates,0,(strlen(disallowDates)-1)); // this will escape the last comma from $disallowDates
echo "];";
so your javascript var diableDateRange shoudl be
var diableDateRange = ["2013-01-01","2013-01-02","2013-01-03"];
<?php
$ConvertDateBack = Zend_Controller_Action_HelperBroker::getStaticHelper('ConvertDate');
$disabledDaysRange = array();
foreach($this->reservedDates as $dates) {
$date = $ConvertDateBack->ConvertDateBack($dates->reservation_date);
$disabledDaysRange[] = $date;
array_push($disabledDaysRange, $date);
}
$finalArr = json_encode($disabledDaysRange);
?>
<script>
var disabledDaysRange = <?=$finalArr?>;
</script>
You should need to convert your PHP array to javascript array using PHP syntax json_encode.
json_encode convert PHP array to JSON string
Single Dimension PHP array to javascript array
<?php
var $itemsarray= array("Apple", "Bear", "Cat", "Dog");
?>
<script>
var items= <?php echo json_encode($itemsarray); ?>;
console.log(items[2]); // Output: Bear
// OR
alert(items[0]); // Output: Apple
</script>
Multi Dimension PHP array to javascript array
<?php
var $itemsarray= array(
array('name'='Apple', 'price'=>'12345'),
array('name'='Bear', 'price'=>'13344'),
array('name'='Potato', 'price'=>'00440')
);
?>
<script>
var items= <?php echo json_encode($itemsarray); ?>;
console.log(items[1][name]); // Output: Bear
// OR
alert(items[0][price]); // Output: Apple
</script>
For more detail, you can also check php array to javascript array

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>

javascript object push how to set key value

Is there any way to set own key value when using javascript push method? Here is my example:
<script>
var examples = [];
</script>
<?php foreach($examples as $example):?>
<script type="text/javascript">
var example<?php echo $example['id']?> = {
id : '<?php echo $example['id']?>',
another : '<?php echo $example['another']?>',
};
//here I would like to give key $example[id]
examples.push(example<?php echo $example['id']?>);
</script>
<?php endforeach;?>
<script>
for (index = 0; index < examples.length; ++index) {
somefunction(examples[index]);
}
</script>
For some reasons I need $example['id'] to have the same value as pushed key.
Making an array is making this a bit harder than you need it to be if you need the IDs to match.
If you want to reference it by the ID, you can simply use a vanilla JS object
<script>
var examples = {};
</script>
<?php foreach($examples as $example):?>
<script type="text/javascript">
var example<?php echo $example['id']?> = {
id : '<?php echo $example['id']?>',
another : '<?php echo $example['another']?>',
};
//here I would like to give key $example[id]
examples['' + <?php echo $example['id']?>] = example;
</script>
<?php endforeach;?>
<script>
for (var k in examples) {
somefunction(examples[k]);
}
</script>
This will let you set arbitrary string keys and loop through just like an array.
Use an object instead:
var examples = {};
...
examples[key] = value;
If your id is a string value, then you need a mapping object (var obj = {}; obj[key] = value), but you wan't be able to use it as an array since it's not an array, though, you still can do something like this: for (var k in elements) { if (elements.hasOwnProperty(k)) {do something} }
If you really want to use an Array than you can try using splice ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice ) method to insert your elements at certain index (just make sure that array length is always greater than index value you are trying to insert at), but for that your id has to be numeric, not a stirng.

Categories

Resources