PDA

View Full Version : [PHP + JavaScript] codice JS in funzione PHP


_fast_
30-10-2009, 11:36
Ciao a tutti!,
ho la funzione PHP ''menu'' che dal DB pesca i dati e me li torna con un'array che si chiama "menu" (nel quale sono presenti anche i relativi tag html).
Vorrei riuscire a far comparire il menu a tendina (con il mouseover di JavaScript), ma come faccio a integrarlo con la variabile "menu" che mi torna la funzione?
avete esempi da linkarmi o come fare il codice in linea di massima?

grazie

MEMon
30-10-2009, 12:03
Non ho capito bene quello che ti serve, considerando che hai detto che il tuo array contiene tag html probabilmente nont i serve passarlo a javascript ma processarlo con php...comunque rispondo alla tua domanda principale almeno dopo sai come si fa.

Allora innanzitutto è bene che tu sappia che php e javascript non condividono nulla, uno è lato clien(javascript) ossia lavora sul pc di chi visualizza la pagina, e solo dopo che gli è stata forinita dal server, l'altro, è lato server, e lavora appunto sul surver che fonrisce la pagina.

Per passare una variabile php a javascript non si fa altro che "stamparla", con un echo per esempio, in un modo comprensibile da javascript.
Ad esempio mettiamo che devi passare la variabile php:
$php_var=1000

<script type="text/javascript">
var fromPhp=<?php echo $php_var; ?>;
fromPhp=fromPhp+10;
alert(fromPhp); // -> 1010
</script>


Sembra tutto ok, ma proviamo a passare questa variabile
$php_var="ciao"

<script type="text/javascript">
var fromPhp=<?php echo $php_var; ?>;
alert(fromPhp); // ERRORE ciao is not defined
</script>


Cosa significa? Significa che in realtà non hai passato nulla, hai sollo fatto comprendere qualcosa a javascript, e in modo sbagliato!
Infatti javascript ha capito: var fromPhp=ciao; mentre doveva capire
var fromPhp="ciao";

Poco male, basta fare

<script type="text/javascript">
var fromPhp="<?php echo $php_var; ?>";
alert(fromPhp); // -> ciao
</script>


Tu devi(forse) passare un array, in javascript un array si istanzia così

<script type="text/javascript">
var mioArray=["a","c","abc"];
</script>

Quindi devi fare in modo di stampare l'array in un modo comprensibile da javascript, esempio


<?php
//$menu è il tuo array esempio: ["A","C","D"];
//$menu_js è la variabile che "stamperai" per javascript
$menu_js="[";
foreach($menu as $value){
$menu_js.="\"".$value."\",";
}
$menu_js=preg_replace("/,$/","",$menu_js); // elimina l'ultima virgola in eccesso altrimenti sarebbe ["A","C","D",
$menu_js.="]";
?>

E lo ripeschi da javascript con:

<script type="text/javascript">
var menu=<?php echo $menu_js; ?>; // stampa ["A","C","D"]
alert(menu instanceof Array); // true, menu è veramente un array, di stringhe naturalmente
alert(menu[1]); // C
</script>

_fast_
30-10-2009, 14:21
sinceramente vedendo sempre separati php e js mi trovo in difficoltà a formulare la domanda.
praticamente con questa chiamata php:
<div id='menu'> <? echo(menu($id, 0, $lang_id)); ?> </div>
vorrei stampare il menu nel quale la 4'voce ha un menu a tendina..

MEMon
30-10-2009, 14:26
sinceramente vedendo sempre separati php e js mi trovo in difficoltà a formulare la domanda.
praticamente con questa chiamata php:
<div id='menu'> <? echo(menu($id, 0, $lang_id)); ?> </div>
vorrei stampare il menu nel quale la 4'voce ha un menu a tendina..

menu() è una funziona in php?
A quale 4a voce ti riferisci?

_fast_
30-10-2009, 14:41
sì, menu() è la funzione php che pesca i dati dal DB e passa la variabile $menu che contiena il menu, non capisco che passaggi fare con JS..
Ricapitolando ho una funzione php menu() che pesca i dati necessari dal DB per fare il livello orizzontale.
Ho la funzione JS che aggiunge alla voce voluta il menu (verticale) a tendina.
Come unire le 2 cose?
che passaggi fare?

grazie per la pazienza

MEMon
30-10-2009, 14:43
La funzione in js come lavora?
Cosa gli passi?

Cioè mettiamo che la tua funzione menu() che pesca dal db fosse in js e non in php, cosa faresti?

_fast_
30-10-2009, 14:49
come funzione js mi sono scaricato uno dei tanti script per il menu a tendina...
mentre la funzione menu è:

<? function menu($id="1", $level, $lang_id) {
$array_menu = array();
$menu = "";
$queryString = "SELECT level FROM menu WHERE id=".$id;
if (!$query = @mysql_query($queryString)) { error(); }
if (!$array = @mysql_fetch_array($query)) { error(); }
$max_level = $array[0];

for ($i=0; $i <= $max_level ; $i++){
$array_menu[$i] = $id;
$lev = $max_level - $i - 1;
if ($lev >= 0) {
$id = check_menu_selected($id, $lev);
}
}

$array_menu = array_reverse($array_menu);
if ($level <= $max_level){
$queryString = "SELECT id, ".$lang_id.", pos FROM menu WHERE id_ref=".($level - 1 < 0 ? 0 : $array_menu[$level - 1])." AND level=".$level." ORDER BY pos";
} else {
if ($level > $max_level + 1) {
return false;
} else {
$queryString = "SELECT id, ".$lang_id.", pos FROM menu WHERE id_ref=".($array_menu[$max_level])." AND level=".($max_level+1)." ORDER BY pos";
}
}

if (!$query = @mysql_query($queryString)) { error(); }

if (@mysql_num_rows($query) > 0) {
while ($array = @mysql_fetch_array($query)) {
if (($level <= $max_level) && (check_menu_selected($array_menu[$max_level], $level) == $array['id'])) {
$menu .= "<a class='menu_".$level." menu_".$level."_".$array['pos']." menu_".$level."_sel menu_".$level."_".$array['pos']."_sel' href='".$_SERVER['PHP_SELF']."?id=".$array['id']."&amp;lang_id=".$lang_id."' title='".get_a_title("h_menu", $lang_id)."'><span>".stripslashes($array[$lang_id])."</span></a>\n";
} else {
$menu .= "<a class='menu_".$level." menu_".$level."_".$array['pos']."' href='".$_SERVER['PHP_SELF']."?id=".$array['id']."&amp;lang_id=".$lang_id."' title='".get_a_title("h_menu", $lang_id).stripslashes($array[$lang_id])."'><span>".stripslashes($array[$lang_id])."</span></a>\n";
}
}
}
return $menu;
}



// widget: cerca
global $WIDGET_CERCA_TXT;
$WIDGET_CERCA_TXT = array("ita"=>"cerca nel sito","eng"=>"search");
?>

MEMon
30-10-2009, 14:50
Bisogna che mi fai vedere la funzione di js per dirti cosa devi farci con l'array che ottiene in php.

_fast_
30-10-2009, 14:55
quella piu chiara e facilmente modificabile che ho trovato è:


<!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" lang="it">
<head>

<title>Menù a tendina - Esempio JavaScript scaricato da HTML.it</title>
<meta http-equiv="Content-type" content="text/html; charset=iso-8859-1" />
<meta http-equiv="Content-Language" content="it" />
<meta name="Robots" content="All" />
<meta name="Description" content="HTML.it - il sito italiano sul Web publishing" />
<meta name="Keywords" content="Un menù a tendina compatibile con vari browser." />
<meta name="Owner" content="HTML.it srl" />
<meta name="Author" content="HTML.it srl" />
<meta name="Copyright" content="HTML.it srl" />

<style type="text/css">

#dropmenudiv{
position:absolute;
border:1px solid black;
border-bottom-width: 0;
font:normal 12px Verdana;
line-height:18px;
z-index:100;
}

#dropmenudiv a{
width: 100%;
display: block;
text-indent: 3px;
border-bottom: 1px solid black;
padding: 1px 0;
text-decoration: none;
font-weight: bold;
}

#dropmenudiv a:hover{ /*hover background color*/
background-color: yellow;
}

</style>

<script type="text/javascript">

//Contents for menu 1
var menu1=new Array()
menu1[0]='<a href="http://www.abc.it">Html.it</a>'
menu1[1]='<a href="http://freephp.abc.it">Freephp</a>'
menu1[2]='<a href="http://forum.abc.it">Forum</a>'
menu1[3]='<a href="http://forum.abc.it">Forum</a>'
menu1[4]='<a href="http://forum.abc.it">Forum</a>'
menu1[5]='<a href="http://forum.abc.it">Foddrum</a>'


//Contents for menu 2, and so on
var menu2=new Array()
menu2[0]='<a href="#">Articoli abc</a>'
menu2[1]='<a href="#">Script php</a>'
menu2[2]='<a href="#">Tutorial</a>'

var menuwidth='165px' //default menu width
var menubgcolor='lightyellow' //menu bgcolor
var disappeardelay=250 //menu disappear speed onMouseout (in miliseconds)
var hidemenu_onclick="yes" //hide menu when user clicks within menu?

/////No further editting needed

var ie4=document.all
var ns6=document.getElementById&&!document.all

if (ie4||ns6)
document.write('<div id="dropmenudiv" style="visibility:hidden;width:'+menuwidth+';background-color:'+menubgcolor+'" onMouseover="clearhidemenu()" onMouseout="dynamichide(event)"></div>')

function getposOffset(what, offsettype){
var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
var parentEl=what.offsetParent;
while (parentEl!=null){
totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
parentEl=parentEl.offsetParent;
}
return totaloffset;
}

function showhide(obj, e, visible, hidden, menuwidth){
if (ie4||ns6)
dropmenuobj.style.left=dropmenuobj.style.top=-500
if (menuwidth!=""){
dropmenuobj.widthobj=dropmenuobj.style
dropmenuobj.widthobj.width=menuwidth
}
if (e.type=="click" && obj.visibility==hidden || e.type=="mouseover")
obj.visibility=visible
else if (e.type=="click")
obj.visibility=hidden
}

function iecompattest(){
return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function clearbrowseredge(obj, whichedge){
var edgeoffset=0
if (whichedge=="rightedge"){
var windowedge=ie4 && !window.opera? iecompattest().scrollLeft+iecompattest().clientWidth-15 : window.pageXOffset+window.innerWidth-15
dropmenuobj.contentmeasure=dropmenuobj.offsetWidth
if (windowedge-dropmenuobj.x < dropmenuobj.contentmeasure)
edgeoffset=dropmenuobj.contentmeasure-obj.offsetWidth
}
else{
var topedge=ie4 && !window.opera? iecompattest().scrollTop : window.pageYOffset
var windowedge=ie4 && !window.opera? iecompattest().scrollTop+iecompattest().clientHeight-15 : window.pageYOffset+window.innerHeight-18
dropmenuobj.contentmeasure=dropmenuobj.offsetHeight
if (windowedge-dropmenuobj.y < dropmenuobj.contentmeasure){ //move up?
edgeoffset=dropmenuobj.contentmeasure+obj.offsetHeight
if ((dropmenuobj.y-topedge)<dropmenuobj.contentmeasure) //up no good either?
edgeoffset=dropmenuobj.y+obj.offsetHeight-topedge
}
}
return edgeoffset
}

function populatemenu(what){
if (ie4||ns6)
dropmenuobj.innerHTML=what.join("")
}

function dropdownmenu(obj, e, menucontents, menuwidth){
if (window.event) event.cancelBubble=true
else if (e.stopPropagation) e.stopPropagation()
clearhidemenu()
dropmenuobj=document.getElementById? document.getElementById("dropmenudiv") : dropmenudiv
populatemenu(menucontents)

if (ie4||ns6){
showhide(dropmenuobj.style, e, "visible", "hidden", menuwidth)
dropmenuobj.x=getposOffset(obj, "left")
dropmenuobj.y=getposOffset(obj, "top")
dropmenuobj.style.left=dropmenuobj.x-clearbrowseredge(obj, "rightedge")+"px"
dropmenuobj.style.top=dropmenuobj.y-clearbrowseredge(obj, "bottomedge")+obj.offsetHeight+"px"
}

return clickreturnvalue()
}

function clickreturnvalue(){
if (ie4||ns6) return false
else return true
}

function contains_ns6(a, b) {
while (b.parentNode)
if ((b = b.parentNode) == a)
return true;
return false;
}

function dynamichide(e){
if (ie4&&!dropmenuobj.contains(e.toElement))
delayhidemenu()
else if (ns6&&e.currentTarget!= e.relatedTarget&& !contains_ns6(e.currentTarget, e.relatedTarget))
delayhidemenu()
}

function hidemenu(e){
if (typeof dropmenuobj!="undefined"){
if (ie4||ns6)
dropmenuobj.style.visibility="hidden"
}
}

function delayhidemenu(){
if (ie4||ns6)
delayhide=setTimeout("hidemenu()",disappeardelay)
}

function clearhidemenu(){
if (typeof delayhide!="undefined")
clearTimeout(delayhide)
}

if (hidemenu_onclick=="yes")
document.onclick=hidemenu

</script>

</head>
<body >
<br /><br />
<div align="center">


<a href="#" onClick="return clickreturnvalue()" onMouseover="dropdownmenu(this, event, menu1, '150px')" onMouseout="delayhidemenu()">Siti interessanti</a> |

<a href="#" onMouseover="return dropdownmenu(this, event, menu2, '200px')" onMouseout="delayhidemenu()">Varie</a>


</div>
<br /><br /><br /><br /><br /><br />
<div align="center">
<a href="http://www.html.it"><img src="logo_htmlit.gif" alt="JavaScript scaricato da HTML.it" border="0" width="50" height="50" /></a>
</div>


</body>
</html>

MEMon
30-10-2009, 14:57
quella piu chiara e facilmente modificabile che ho trovato è:


<!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" lang="it">
<head>

<title>Menù a tendina - Esempio JavaScript scaricato da HTML.it</title>
<meta http-equiv="Content-type" content="text/html; charset=iso-8859-1" />
<meta http-equiv="Content-Language" content="it" />
<meta name="Robots" content="All" />
<meta name="Description" content="HTML.it - il sito italiano sul Web publishing" />
<meta name="Keywords" content="Un menù a tendina compatibile con vari browser." />
<meta name="Owner" content="HTML.it srl" />
<meta name="Author" content="HTML.it srl" />
<meta name="Copyright" content="HTML.it srl" />

<style type="text/css">

#dropmenudiv{
position:absolute;
border:1px solid black;
border-bottom-width: 0;
font:normal 12px Verdana;
line-height:18px;
z-index:100;
}

#dropmenudiv a{
width: 100%;
display: block;
text-indent: 3px;
border-bottom: 1px solid black;
padding: 1px 0;
text-decoration: none;
font-weight: bold;
}

#dropmenudiv a:hover{ /*hover background color*/
background-color: yellow;
}

</style>

<script type="text/javascript">

//Contents for menu 1
var menu1=new Array()
menu1[0]='<a href="http://www.abc.it">Html.it</a>'
menu1[1]='<a href="http://freephp.abc.it">Freephp</a>'
menu1[2]='<a href="http://forum.abc.it">Forum</a>'
menu1[3]='<a href="http://forum.abc.it">Forum</a>'
menu1[4]='<a href="http://forum.abc.it">Forum</a>'
menu1[5]='<a href="http://forum.abc.it">Foddrum</a>'


//Contents for menu 2, and so on
var menu2=new Array()
menu2[0]='<a href="#">Articoli abc</a>'
menu2[1]='<a href="#">Script php</a>'
menu2[2]='<a href="#">Tutorial</a>'

var menuwidth='165px' //default menu width
var menubgcolor='lightyellow' //menu bgcolor
var disappeardelay=250 //menu disappear speed onMouseout (in miliseconds)
var hidemenu_onclick="yes" //hide menu when user clicks within menu?

/////No further editting needed

var ie4=document.all
var ns6=document.getElementById&&!document.all

if (ie4||ns6)
document.write('<div id="dropmenudiv" style="visibility:hidden;width:'+menuwidth+';background-color:'+menubgcolor+'" onMouseover="clearhidemenu()" onMouseout="dynamichide(event)"></div>')

function getposOffset(what, offsettype){
var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
var parentEl=what.offsetParent;
while (parentEl!=null){
totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
parentEl=parentEl.offsetParent;
}
return totaloffset;
}

function showhide(obj, e, visible, hidden, menuwidth){
if (ie4||ns6)
dropmenuobj.style.left=dropmenuobj.style.top=-500
if (menuwidth!=""){
dropmenuobj.widthobj=dropmenuobj.style
dropmenuobj.widthobj.width=menuwidth
}
if (e.type=="click" && obj.visibility==hidden || e.type=="mouseover")
obj.visibility=visible
else if (e.type=="click")
obj.visibility=hidden
}

function iecompattest(){
return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function clearbrowseredge(obj, whichedge){
var edgeoffset=0
if (whichedge=="rightedge"){
var windowedge=ie4 && !window.opera? iecompattest().scrollLeft+iecompattest().clientWidth-15 : window.pageXOffset+window.innerWidth-15
dropmenuobj.contentmeasure=dropmenuobj.offsetWidth
if (windowedge-dropmenuobj.x < dropmenuobj.contentmeasure)
edgeoffset=dropmenuobj.contentmeasure-obj.offsetWidth
}
else{
var topedge=ie4 && !window.opera? iecompattest().scrollTop : window.pageYOffset
var windowedge=ie4 && !window.opera? iecompattest().scrollTop+iecompattest().clientHeight-15 : window.pageYOffset+window.innerHeight-18
dropmenuobj.contentmeasure=dropmenuobj.offsetHeight
if (windowedge-dropmenuobj.y < dropmenuobj.contentmeasure){ //move up?
edgeoffset=dropmenuobj.contentmeasure+obj.offsetHeight
if ((dropmenuobj.y-topedge)<dropmenuobj.contentmeasure) //up no good either?
edgeoffset=dropmenuobj.y+obj.offsetHeight-topedge
}
}
return edgeoffset
}

function populatemenu(what){
if (ie4||ns6)
dropmenuobj.innerHTML=what.join("")
}

function dropdownmenu(obj, e, menucontents, menuwidth){
if (window.event) event.cancelBubble=true
else if (e.stopPropagation) e.stopPropagation()
clearhidemenu()
dropmenuobj=document.getElementById? document.getElementById("dropmenudiv") : dropmenudiv
populatemenu(menucontents)

if (ie4||ns6){
showhide(dropmenuobj.style, e, "visible", "hidden", menuwidth)
dropmenuobj.x=getposOffset(obj, "left")
dropmenuobj.y=getposOffset(obj, "top")
dropmenuobj.style.left=dropmenuobj.x-clearbrowseredge(obj, "rightedge")+"px"
dropmenuobj.style.top=dropmenuobj.y-clearbrowseredge(obj, "bottomedge")+obj.offsetHeight+"px"
}

return clickreturnvalue()
}

function clickreturnvalue(){
if (ie4||ns6) return false
else return true
}

function contains_ns6(a, b) {
while (b.parentNode)
if ((b = b.parentNode) == a)
return true;
return false;
}

function dynamichide(e){
if (ie4&&!dropmenuobj.contains(e.toElement))
delayhidemenu()
else if (ns6&&e.currentTarget!= e.relatedTarget&& !contains_ns6(e.currentTarget, e.relatedTarget))
delayhidemenu()
}

function hidemenu(e){
if (typeof dropmenuobj!="undefined"){
if (ie4||ns6)
dropmenuobj.style.visibility="hidden"
}
}

function delayhidemenu(){
if (ie4||ns6)
delayhide=setTimeout("hidemenu()",disappeardelay)
}

function clearhidemenu(){
if (typeof delayhide!="undefined")
clearTimeout(delayhide)
}

if (hidemenu_onclick=="yes")
document.onclick=hidemenu

</script>

</head>
<body >
<br /><br />
<div align="center">


<a href="#" onClick="return clickreturnvalue()" onMouseover="dropdownmenu(this, event, menu1, '150px')" onMouseout="delayhidemenu()">Siti interessanti</a> |

<a href="#" onMouseover="return dropdownmenu(this, event, menu2, '200px')" onMouseout="delayhidemenu()">Varie</a>


</div>
<br /><br /><br /><br /><br /><br />
<div align="center">
<a href="http://www.html.it"><img src="logo_htmlit.gif" alt="JavaScript scaricato da HTML.it" border="0" width="50" height="50" /></a>
</div>


</body>
</html>


Allora, se lavora con un array, e quell'array è quello che ti crei con php, ti ho già detto come fare, ti ho scritto il codice preciso:


<?php
//$menu è il tuo array esempio: ["A","C","D"];
//$menu_js è la variabile che "stamperai" per javascript
$menu_js="[";
foreach($menu as $value){
$menu_js.="\"".$value."\",";
}
$menu_js=preg_replace("/,$/","",$menu_js); // elimina l'ultima virgola in eccesso altrimenti sarebbe ["A","C","D",
$menu_js.="]";
?>

E lo ripeschi da javascript con:

<script type="text/javascript">
var menu1=<?php echo $menu_js; ?>; // stampa ["A","C","D"]
// menu1 è il menu1 della funziona js ad esempio
</script>


Stai solo attento ai " e '

MEMon
30-10-2009, 15:02
Te lo metto come funzione così la utilizzi pari pari:

//IN PHP
function phpToJsArray($array){
$array_js="[";
foreach($array as $value){
$array_js.="\"".$value."\",";
}
$array_js=preg_replace("/,$/","",$array_js);
$array_js.="];";
echo $array_js;
}


Da usare così:

<script type="text/javascript">
var menu=<?php phpToJsArray($menu); ?>
</script>

_fast_
30-10-2009, 15:06
grazie mille!

:D