M.H.Chief M.H.Chief - 3 months ago 8
HTML Question

TypeError: array[i] is undefined

I load a multidimensional array in php

for($y = 0; $y< $totaleventosaldia; $y++ ){

$arraynombres[$y] = array($arrayeventosaldia[$y][1]);

}


Pass the array to the javascript method

echo "<td><button id = '".$year."-".$month."-".$i."' type='button' class='btn-default' style=' border-style: solid; border-image: url(imagenes/rainbow.jpg) 30 round;' onclick='mostrarModal(".$idboton.",".$arraynombres.");' >".$i."</button></td>";


I keep getting array[i] is undefined i dont get it,

<script>
function mostrarModal(idboton, eventos){


var fechaboton = idboton;

var array = [];

var acumuladordenombres;


for(var i =0; i < eventos.length;i++){
array[i] = eventos[i];
acumuladordenombres = acumuladordenombres +' '+ array[i][0];
}


alert(acumuladordenombres);




}
</script>


Help plz, have been couple hours with this.

Answer

You are not allowed to put a PHP array directly to JavaScript. Please try to json_encode it:

onclick='mostrarModal(".$idboton.",".json_encode($arraynombres).");'

Regarding your JavaScript I would suggest to directly use eventos instead of copying the elements to array:

for(var i =0; i < eventos.length;i++) {
    acumuladordenombres = acumuladordenombres +' '+ eventos[i][0];
}