Foros del Web » Programando para Internet » PHP »

Cómo pasar de php a array de javascript

Estas en el tema de Cómo pasar de php a array de javascript en el foro de PHP en Foros del Web. Hola! tengo este código que junta unas imágenes Código PHP: <?php   foreach( $imagenes  as  $img ) {   $imagen = "imagenes/productos/$img->id/a1.jpg" ; } ?> y necesito ...
  #1 (permalink)  
Antiguo 06/04/2012, 09:44
 
Fecha de Ingreso: agosto-2003
Mensajes: 524
Antigüedad: 20 años, 8 meses
Puntos: 5
Cómo pasar de php a array de javascript

Hola!

tengo este código que junta unas imágenes

Código PHP:
<?php
 
foreach($imagenes as $img) {  
$imagen="imagenes/productos/$img->id/a1.jpg";

}
?>
y necesito volcar esas imágenes en un loop de javascript, pero no se como hacerlo

Código PHP:
<script type="text/javascript">

var mygallery=new simpleGallery({
wrapperid: "simplegallery", 
dimensions: [1280, 510], 
imagearray: [
<?php 
echo "[\"$imagen\", \"\", \"\", \"\"]" // aquí solo me muestra la primer imagen - como hago un for o algo que recorra las imágenes que capturé en el cógido php?
?>

],   

}
Espero que puedan ayudarme, hace varios días que estoy trabada con este problema y todo lo que encontré en internet no funcionó.

Gracias de antemano!
__________________
Saludos!!!
Maru.-
  #2 (permalink)  
Antiguo 06/04/2012, 10:10
Avatar de gjx2  
Fecha de Ingreso: agosto-2008
Ubicación: R.D
Mensajes: 1.153
Antigüedad: 15 años, 8 meses
Puntos: 139
Respuesta: Cómo pasar de php a array de javascript

Se me ocurren tres forma ahora mismo.

1- Hacerlo por ajax

2- ingresar los datos a la variable de js desde php

Código HTML:
Ver original
  1. <script type="text/javascript">
  2.  
  3. var img = new Array();
  4.  
  5. window.onload = function(){
  6. <?PHP
  7.         $i=0;
  8.         while($i<10){
  9.            
  10.             echo "img[".$i."]=".$i.";\n";
  11.        
  12.         $i++;  
  13.         }
  14.    
  15.    
  16.     ?>
  17. alert("Segunda forma" + img.length);
  18.  
  19. }
  20.  


3- Crear una cadena dividida por comas y en javascript haces uso de split ej.

Código HTML:
Ver original
  1. <?PHP
  2.         $i=0;
  3.         $img = "";
  4.         while($i<10){
  5.            
  6.             $img .= $i.",";
  7.        
  8.         $i++;  
  9.         }
  10.    
  11.     $img = trim($img,",");
  12.     ?>
  13.  
  14.  
  15. <script type="text/javascript">
  16.  
  17. var img = new Array();
  18.  
  19. window.onload = function(){
  20.  
  21.  
  22.  
  23.    
  24.     var t = "<?=$img?>";
  25.      img =  t.split(",");
  26.        
  27.        
  28.         alert("Tercera forma" + img.length);
  29.  
  30.  
  31. }
  32.  

Trabaja con la que mas te guste.
  #3 (permalink)  
Antiguo 06/04/2012, 10:17
Avatar de gjx2  
Fecha de Ingreso: agosto-2008
Ubicación: R.D
Mensajes: 1.153
Antigüedad: 15 años, 8 meses
Puntos: 139
Respuesta: Cómo pasar de php a array de javascript

Se me olvido una cuarta que es por json

Código HTML:
Ver original
  1. <?PHP
  2.         $i = 0;
  3.         $img = "";
  4.         while($i<10){
  5.            
  6.             $img[] = "valor ".$i;
  7.        
  8.         $i++;  
  9.         }
  10.    
  11.  
  12.    
  13.     ?>
  14.  
  15.  
  16. <script type="text/javascript">
  17.  
  18. var img = new Array();
  19.  
  20. window.onload = function(){
  21.  
  22.     var img  = <?=json_encode($img)?>;
  23.     alert(img[3]);
  24. }
  25.  

Última edición por gjx2; 06/04/2012 a las 10:27 Razón: había cometido un error diseñando el json
  #4 (permalink)  
Antiguo 06/04/2012, 10:37
 
Fecha de Ingreso: agosto-2003
Mensajes: 524
Antigüedad: 20 años, 8 meses
Puntos: 5
Respuesta: Cómo pasar de php a array de javascript

wow muchas gracias por mostrarme tantas alternativas!!!

no logro poner esto dentro del ejemplo 4 (que es el que tomé como modelo)

Código PHP:
$imagen="imagenes/productos/$img->id/a1.jpg"
ya que esta variable $img está declarada en el foreach de mi ejemplo.
__________________
Saludos!!!
Maru.-
  #5 (permalink)  
Antiguo 06/04/2012, 10:45
Avatar de gjx2  
Fecha de Ingreso: agosto-2008
Ubicación: R.D
Mensajes: 1.153
Antigüedad: 15 años, 8 meses
Puntos: 139
Respuesta: Cómo pasar de php a array de javascript

Adaptado utilizando el ej 4. seria algo como esto


Código HTML:
Ver original
  1. <?php
  2.  
  3. foreach($imagenes as $img) {  
  4.  
  5. $imagen[] = "imagenes/productos/".$img->id."/a1.jpg";
  6.  
  7. }
  8.  
  9.  
  10.  
  11. ?>
  12. <script type="text/javascript">
  13.  
  14. var img = new Array();
  15.  
  16. window.onload = function(){
  17.  
  18. var img = <?=json_encode($imagen)?>;
  19.  alert(img[3]);
  20. }
  21.  
  #6 (permalink)  
Antiguo 06/04/2012, 11:26
 
Fecha de Ingreso: agosto-2003
Mensajes: 524
Antigüedad: 20 años, 8 meses
Puntos: 5
Respuesta: Cómo pasar de php a array de javascript

lo intenté así, si bien no me arroja ningún error no me muestra la imagen

Código HTML:
<script type="text/javascript">

var img = new Array(); 
var img = <?=json_encode($imagen)?>;

var mygallery=new simpleGallery({
wrapperid: "simplegallery", //ID of main gallery container,
dimensions: [1280, 510], //width/height of gallery in pixels. Should reflect dimensions of the images exactly
imagearray: [

["img[1]", "", "", ""],
["img[2]", "", "", ""]

],
...
}
es necesario que ubique las imagenes de este modo, ya que es así como funciona el script.

Código HTML:
imagearray: [

["img[1]", "", "", ""],
["img[2]", "", "", ""]

],
__________________
Saludos!!!
Maru.-
  #7 (permalink)  
Antiguo 06/04/2012, 12:06
Avatar de gjx2  
Fecha de Ingreso: agosto-2008
Ubicación: R.D
Mensajes: 1.153
Antigüedad: 15 años, 8 meses
Puntos: 139
Respuesta: Cómo pasar de php a array de javascript

Este codigo te deberia de funcionar sin ningun tipo de problemas , solo que debes de estudiarlo bien y adaptarlo.



Código HTML:
Ver original
  1. <?php
  2.  
  3.  
  4. foreach($imagenes as $img) {  
  5. $imagen[] = "imagenes/productos/".$img->id."/a1.jpg";  
  6. }
  7.  
  8.  
  9. ?>
  10. <script type="text/javascript">
  11. window.onload = function(){
  12.  
  13. var img = new Array();
  14. var imagenes = <?=json_encode($imagen)?>
  15.  
  16.  
  17. for(i=0;i<imagenes.length;i++){
  18.    
  19.     img[i] = new Array(imagenes[i],"TITULO","CONTENIDO","ETC","ETC");
  20.    
  21. }
  22.  
  23.  
  24. var mygallery=new simpleGallery({
  25.     wrapperid: "simplegallery1", //ID of main gallery container,
  26.     dimensions: [250, 180], //width/height of gallery in pixels. Should reflect dimensions of the images exactly
  27.     imagearray:img,
  28.     autoplay: [true, 2500, 2], //[auto_play_boolean, delay_btw_slide_millisec, cycles_before_stopping_int]
  29.     persist: false, //remember last viewed slide and recall within same session?
  30.     fadeduration: 500, //transition duration (milliseconds)
  31.     oninit:function(){ //event that fires when gallery has initialized/ ready to run
  32.         //Keyword "this": references current gallery instance (ie: try this.navigate("play/pause"))
  33.     },
  34.     onslide:function(curslide, i){ //event that fires after each slide is shown
  35.         //Keyword "this": references current gallery instance
  36.         //curslide: returns DOM reference to current slide's DIV (ie: try alert(curslide.innerHTML)
  37.         //i: integer reflecting current image within collection being shown (0=1st image, 1=2nd etc)
  38.     }
  39. })
  40. }
  41. </script>


Probe el codigo con la galeria y me funciona perfecto.


Aqui abajo te dejo la prueba de escritorio que realice.


Código PHP:
Ver original
  1. <?php
  2.  
  3.  
  4. $imgDb[1] = "http://i26.tinypic.com/11l7ls0.jpg";
  5. $imgDb[2] = "http://i29.tinypic.com/xp3hns.jpg";
  6. $imgDb[3] = "http://i30.tinypic.com/531q3n.jpg";
  7. $imgDb[4] =  "http://i31.tinypic.com/119w28m.jpg";
  8.  
  9.  
  10. foreach($imgDb as $id){
  11. $img[] = $id;  
  12. }
  13.  
  14. ?>
  15. <script type="text/javascript">
  16. window.onload = function(){
  17.  
  18. var img = new Array();
  19. var imagenes = <?=json_encode($img)?>
  20.  
  21.  
  22. for(i=0;i<imagenes.length;i++){
  23.    
  24.     img[i] = new Array(imagenes[i],"","","","");
  25.    
  26. }
  27.  
  28.  
  29. var mygallery=new simpleGallery({
  30.     wrapperid: "simplegallery1", //ID of main gallery container,
  31.     dimensions: [250, 180], //width/height of gallery in pixels. Should reflect dimensions of the images exactly
  32.     imagearray:img,
  33.     autoplay: [true, 2500, 2], //[auto_play_boolean, delay_btw_slide_millisec, cycles_before_stopping_int]
  34.     persist: false, //remember last viewed slide and recall within same session?
  35.     fadeduration: 500, //transition duration (milliseconds)
  36.     oninit:function(){ //event that fires when gallery has initialized/ ready to run
  37.         //Keyword "this": references current gallery instance (ie: try this.navigate("play/pause"))
  38.     },
  39.     onslide:function(curslide, i){ //event that fires after each slide is shown
  40.         //Keyword "this": references current gallery instance
  41.         //curslide: returns DOM reference to current slide's DIV (ie: try alert(curslide.innerHTML)
  42.         //i: integer reflecting current image within collection being shown (0=1st image, 1=2nd etc)
  43.     }
  44. })
  45.  
  46.  
  47.  
  48. }
  49. </script>
  50. <div id="simplegallery1" style="width:500px"></div>
  #8 (permalink)  
Antiguo 09/04/2012, 12:21
 
Fecha de Ingreso: agosto-2003
Mensajes: 524
Antigüedad: 20 años, 8 meses
Puntos: 5
Respuesta: Cómo pasar de php a array de javascript

gjx2, gracias por tu inmensa paciencia!

Probé el código de tu ejemplo y funciona!

Solo que cuando lo adapto al mio agregando titulo y link además de la imagen no funciona.

Te dejo el código completo:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>

<link href='http://fonts.googleapis.com/css?family=Cabin+Condensed' rel='stylesheet' type='text/css'>


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<script type="text/javascript" src="js/simplegallery.js"></script>

<?php


$conn = new conection();
$rs = new RecordSet($conn);

$sql="SELECT * FROM `banners` ORDER BY `id` DESC LIMIT 5";
$banners = $rs->get_object_list($sql);

foreach($banners as $ban){
$img[]="imagenes/banners/$ban->id/n0-s0.jpg";
$tit[]="$ban->titulo";

}

?>
<script type="text/javascript">
window.onload = function(){

var img = new Array();
var tit = new Array();

var imagenes = <?=json_encode($img)?>
var titulos = <?=json_encode($tit)?>


for(i=0;i<imagenes.length;i++){

img[i] = new Array(imagenes[i],"","","","");
tit[i] = new Array(titulos[i],"","","","");
}

var mygallery=new simpleGallery({
wrapperid: "simplegallery", //ID of main gallery container,
dimensions: [1280, 510], //width/height of gallery in pixels. Should reflect dimensions of the images exactly
imagearray: [img, tit],
autoplay: [true, 2500, 2], //[auto_play_boolean, delay_btw_slide_millisec, cycles_before_stopping_int]
persist: false, //remember last viewed slide and recall within same session?
fadeduration: 500, //transition duration (milliseconds)
oninit:function(){ //event that fires when gallery has initialized/ ready to run
//Keyword "this": references current gallery instance (ie: try this.navigate("play/pause"))
},
onslide:function(curslide, i){ //event that fires after each slide is shown
//Keyword "this": references current gallery instance
//curslide: returns DOM reference to current slide's DIV (ie: try alert(curslide.innerHTML)
//i: integer reflecting current image within collection being shown (0=1st image, 1=2nd etc)
}
})

}

</script>

</head>

<body>

<div id="simplegallery"></div>

</body>
__________________
Saludos!!!
Maru.-
  #9 (permalink)  
Antiguo 09/04/2012, 12:52
Avatar de gjx2  
Fecha de Ingreso: agosto-2008
Ubicación: R.D
Mensajes: 1.153
Antigüedad: 15 años, 8 meses
Puntos: 139
Respuesta: Cómo pasar de php a array de javascript

Hola Maru77 ,

Le hice unos ajuste al código para que te pueda permite la colocación de titulo y link fijate bien en los cambios.


Código PHP:
Ver original
  1. <?php
  2.  
  3.  
  4. $imgDb[1] = "http://i26.tinypic.com/11l7ls0.jpg";
  5. $imgDb[2] = "http://i29.tinypic.com/xp3hns.jpg";
  6. $imgDb[3] = "http://i30.tinypic.com/531q3n.jpg";
  7. $imgDb[4] =  "http://i31.tinypic.com/119w28m.jpg";
  8.  
  9.  
  10. foreach($imgDb as $id){
  11.  
  12. # Cree una matriz de dos dimenciones para poder tener el control de las  propiedades de cada imagen
  13. $img['img'][] = $id;
  14. $img['titulo'][] = "ejemplo imagen ".$id; //$ban->titulo;
  15. $img['link'][] = "http://".$id."/";  # Aqui colocas el link algun link
  16.  
  17. }
  18.  
  19. ?>
  20. <script type="text/javascript">
  21. window.onload = function(){
  22.  
  23. var img = new Array();
  24. var imagenes = <?=json_encode($img)?>
  25.  
  26. for(i=0;i<imagenes['img'].length;i++){
  27.    
  28.        
  29.      // Aqui realice otro cambio que espero lo notes.      
  30.     img[i] = new Array( imagenes['img'][i],imagenes['link'][i],"_new",imagenes['titulo'][i] );
  31.    
  32. }
  33.  
  34.  
  35. var mygallery=new simpleGallery({
  36.     wrapperid: "simplegallery1", //ID of main gallery container,
  37.     dimensions: [250, 180], //width/height of gallery in pixels. Should reflect dimensions of the images exactly
  38.     imagearray:img,    
  39.     autoplay: [true, 2500, 2], //[auto_play_boolean, delay_btw_slide_millisec, cycles_before_stopping_int]
  40.     persist: false, //remember last viewed slide and recall within same session?
  41.     fadeduration: 500, //transition duration (milliseconds)
  42.     oninit:function(){ //event that fires when gallery has initialized/ ready to run
  43.         //Keyword "this": references current gallery instance (ie: try this.navigate("play/pause"))
  44.     },
  45.     onslide:function(curslide, i){ //event that fires after each slide is shown
  46.         //Keyword "this": references current gallery instance
  47.         //curslide: returns DOM reference to current slide's DIV (ie: try alert(curslide.innerHTML)
  48.         //i: integer reflecting current image within collection being shown (0=1st image, 1=2nd etc)
  49.     }
  50. })
  51.  
  52.  
  53.  
  54. }
  55. </script>
  56. <div id="simplegallery1" style="width:500px"></div>
  #10 (permalink)  
Antiguo 12/04/2012, 10:50
 
Fecha de Ingreso: agosto-2003
Mensajes: 524
Antigüedad: 20 años, 8 meses
Puntos: 5
Respuesta: Cómo pasar de php a array de javascript

Hola GJX2!!!

Perdón por responder tarde, no estuve con mucho tiempo.

Intenté adaptar tu código, pero creo que estoy teniendo inconvenientes en como lo interto porque no me muestra ningún resultado.

Código PHP:
<?php
 
foreach($banners as $ban){  
$img['img'][]="imagenes/banners/$ban->id/n0-s0.jpg";
$img['titulo'][] = "ejemplo imagen ".$ban// probe con $ban->titulo pero no resulta 
$img['link'][] = "http://".$ban."/";  //probe con $ban->link y tampoco resulta - estos son en definitiva los datos que debo tomar de la tabla
}

?>   

<script type="text/javascript">
window.onload = function(){
 
var img = new Array();
var imagenes = <?=json_encode($img)?> 
 
for(i=0;i<imagenes.length;i++){
    
        
    img[i] = new Array( imagenes['img'][i],imagenes['link'][i],"_new",imagenes['titulo'][i] );
    
}

var mygallery=new simpleGallery({
    wrapperid: "simplegallery", //ID of main gallery container,
    dimensions: [1280, 510], //width/height of gallery in pixels. Should reflect dimensions of the images exactly
    imagearray: img,
    autoplay: [true, 4000, 2], //[auto_play_boolean, delay_btw_slide_millisec, cycles_before_stopping_int]
    persist: true, //remember last viewed slide and recall within same session?
    fadeduration: 1000, //transition duration (milliseconds)
    oninit:function(){ //event that fires when gallery has initialized/ ready to run
        //Keyword "this": references current gallery instance (ie: try this.navigate("play/pause"))
    },
    onslide:function(curslide, i){ //event that fires after each slide is shown
        //Keyword "this": references current gallery instance
        //curslide: returns DOM reference to current slide's DIV (ie: try alert(curslide.innerHTML)
        //i: integer reflecting current image within collection being shown (0=1st image, 1=2nd etc)
    }
})
 
}
__________________
Saludos!!!
Maru.-
  #11 (permalink)  
Antiguo 12/04/2012, 11:10
Avatar de gjx2  
Fecha de Ingreso: agosto-2008
Ubicación: R.D
Mensajes: 1.153
Antigüedad: 15 años, 8 meses
Puntos: 139
Respuesta: Cómo pasar de php a array de javascript

Creo que tiene problema en como estas tratando a $ban en el foreach
me gustaria que probaras el $bar a ver que te arrojar.

Código PHP:
Ver original
  1. foreach ($banners as $ban){  
  2. echo $ban->id."<br />";
  3. echo $ban->titulo."<br />";
  4. echo $ban->link."<br />";
  5. }
  #12 (permalink)  
Antiguo 12/04/2012, 11:26
 
Fecha de Ingreso: agosto-2003
Mensajes: 524
Antigüedad: 20 años, 8 meses
Puntos: 5
Respuesta: Cómo pasar de php a array de javascript

Si el foreach de ese modo funciona, me muestra un par de registros que cargué

2
titulo 2
www.link2.com
1
titulo 1
www.link1.com
__________________
Saludos!!!
Maru.-
  #13 (permalink)  
Antiguo 12/04/2012, 11:59
 
Fecha de Ingreso: agosto-2003
Mensajes: 524
Antigüedad: 20 años, 8 meses
Puntos: 5
Respuesta: Cómo pasar de php a array de javascript

Funcionó!!! un genio gjx2!!!

El problema estaba que como el banner tiene unos botones para avanzar y retroceder < > que están en un div, se estaban superponiendo con el script y no me dejaba ver nada.

Mil gracias por tu ayuda!!!
__________________
Saludos!!!
Maru.-

Etiquetas: imagenes, javascript
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 16:39.