Using PHP variables on Javascript Function

Need help with an engine or coding not on the list? Need help with a game or the website and forums here? Direct all questions here.
Post Reply
User avatar
vitinho444
Posts: 2825
Joined: Mon Mar 21, 2011 4:54 pm

Using PHP variables on Javascript Function

Post by vitinho444 »

Hello community, still making my browser based game i'm wasting a lot of time on my map.

Finally i got it working, a bit ugly and bugged but it works fine.

It is like this: There's a query to see what villages are near yours, they are presented with an image in the map.

But now how can i know whats mine, and what is the others village info and stuff?
So i want to make a little on mouse over function on the image a href link to open a div in the same page showing some information. Like a popup but not a new window.

Im making like this:

Code: Select all

 <script language="javascript" type="text/javascript">
            function ShowInfo(x, y) 
            {
                <?php
                echo "<div id='somediv'>";
                $vill_info = mysql_fetch_array(mysql_query("SELECT * from aldeias where x='$x' AND y='$y'"));
                echo $x;
                echo "</div>";
                ?>
            }
</script>
then in the code:

Code: Select all

echo "<a class='village' onmouseover='ShowInfo($_X, $_Y)' href='village.php?x=" . $village['x'] . "&y=". $village['y'] ."' style='top: " . $villageTop . "px; left: " . $villageLeft . "px;  padding-left:7px; padding-top:10px; padding-bottom:7px; padding-right:10px;'></a>";
     
If on the function i put alert(x) or y it alerts and stuff.. but i really want to make that mysql queries and show of that info.

I searched on google, but things like this need to be a related example, but i couldnt find one.
Is there a way?
My Company Website: http://www.oryzhon.com

Skype: vpegas1234
User avatar
OldRod
Posts: 1321
Joined: Sun Sep 20, 2009 4:26 pm

Re: Using PHP variables on Javascript Function

Post by OldRod »

I can't seem to find my code now... but a couple years back, I used the information on this page:

http://sixrevisions.com/tutorials/javas ... t_tooltip/

to make a tooltip. Is that something like what you are looking for?
User avatar
vitinho444
Posts: 2825
Joined: Mon Mar 21, 2011 4:54 pm

Re: Using PHP variables on Javascript Function

Post by vitinho444 »

Thats just the "div" where the info can be displayed.. but i cant make it display a string variable :( just a int.

And besides, i want to pass a lot of information to this function or at least the x and y and then inside the function do the query and display all.

Is not possible?
My Company Website: http://www.oryzhon.com

Skype: vpegas1234
User avatar
OldRod
Posts: 1321
Joined: Sun Sep 20, 2009 4:26 pm

Re: Using PHP variables on Javascript Function

Post by OldRod »

Using PHP and the echo command you can build your tooltip to use a string.

I found my code I was remembering. I had it set so you can make notes about other players. When you are in the same location as those players, their name shows up in a list. Hovering the mouse over their name shows any notes you may have. Here is that code.

When the page loads the player list, it checks the database to see if any notes exist for the given player. If they do, they are loaded into $otherplayernotes. Notice that I am building the tooltip using echo statements so I can substitute my $otherplayernotes info into the code:

Code: Select all

echo "<td align=left><a class=\"info\" href=add_player_note.php?id=$otherplayers[player_id]><span class=\"tip\" onmouseover=\"tooltip('Add a note or name for this player');\" onmouseout=\"exit();\"><img border=0 src=img/note.gif></img></span></a>";
if ($otherplayernotes['other_player_notes']<>"")
{
	echo "<td align=left><font color=red><span class=\"tip\" onmouseover=\"tooltip('$otherplayernotes[other_player_notes]');\" onmouseout=\"exit();\">$otherplayer_display_name ($otherplayer_sex)</span></font></td>";
}
else
{
	echo "<td align=left><font color=red><span class=\"tip\">$otherplayer_display_name ($otherplayer_sex)</span></font></td>";
}
Then I have the following functions that I found somewhere on the web... can't remember where at the moment:

Code: Select all

function getmouseposition(e)
{
    if(document.getElementById)
    {
        var iebody=(document.compatMode && 
        	document.compatMode != 'BackCompat') ? 
        		document.documentElement : document.body;
        pagex = (isapple == 1 ? 0:(ie5)?iebody.scrollLeft:window.pageXOffset);
        pagey = (isapple == 1 ? 0:(ie5)?iebody.scrollTop:window.pageYOffset);
        mousex = (ie5)?event.x:(ns6)?clientX = e.clientX:false;
        mousey = (ie5)?event.y:(ns6)?clientY = e.clientY:false;

        var lixlpixel_tooltip = document.getElementById('tooltip');
        lixlpixel_tooltip.style.left = (mousex+pagex+offsetx) + 'px';
        lixlpixel_tooltip.style.top = (mousey+pagey+offsety) + 'px';
    }
}

function tooltip(tip)
{
    if(!document.getElementById('tooltip')) newelement('tooltip');
    var lixlpixel_tooltip = document.getElementById('tooltip');
    lixlpixel_tooltip.innerHTML = tip;
    lixlpixel_tooltip.style.display = 'block';
    document.onmousemove = getmouseposition;
}

function exit()
{
    document.getElementById('tooltip').style.display = 'none';
}
User avatar
Luke111
Posts: 84
Joined: Fri Aug 17, 2012 7:02 am

Re: Using PHP variables on Javascript Function

Post by Luke111 »

Hi!
You can't directly access PHP variables from Javascript, as once PHP runs, and displays the page, it is done.

Maybe something like this:

Code: Select all

<script type="text/javascript">
  var x = "<?php echo $x; ?>";
  function doSomething(a,elemID)
  {
    //just an example
    document.getElementByID(elemID).innerHTML = a;
  }
</script>
Then, you can have a textbox and a button:

Code: Select all

<input type="text" id="myTextbox" />
<button onclick="doSomething(x,'myTextbox');">Click to fill the textbox with the content of the PHP variable X!</button>

This, of course, would be a LOT better with jQuery, but I wrote it with the standard javascript calls. I haven't tested this, but the only place where it might error is because of scoping problems.

You may be also interested in AJAX.
I don't believe in platform-specific development, but I also don't believe in Apple.
User avatar
hallsofvallhalla
Site Admin
Posts: 12031
Joined: Wed Apr 22, 2009 11:29 pm

Re: Using PHP variables on Javascript Function

Post by hallsofvallhalla »

you CAN access PHP variables through Javascript, you just can't change them.
User avatar
vitinho444
Posts: 2825
Joined: Mon Mar 21, 2011 4:54 pm

Re: Using PHP variables on Javascript Function

Post by vitinho444 »

Luke i tried that, but i need to make a query too..

OldRod
I used your script like this:

echo "<a class='village' onmouseover=\"tooltip('$village[nome]');\" onmouseout=\"exit();\" href='village.php?x=" . $village['x'] . "&y=". $village['y'] ."' style='top: " . $villageTop . "px; left: " . $villageLeft . "px; padding-left:7px; padding-top:10px; padding-bottom:7px; padding-right:10px;'></a>";


I got your code right there in the beginning then before the </body> i got the scripts you gave me.
But nothing happens
My Company Website: http://www.oryzhon.com

Skype: vpegas1234
User avatar
OldRod
Posts: 1321
Joined: Sun Sep 20, 2009 4:26 pm

Re: Using PHP variables on Javascript Function

Post by OldRod »

Did you set up a DIV for the tooltip?

I forgot to post that part... but in my .css file I have:

Code: Select all

#tooltip {
    padding: 3px;
    background: #f2f2f2;
    border: 2px solid #9A339A;
    text-align: center;
}
If that doesn't work, let me know and I'll try to come up with a simplified example and post the entire thing. I may be missing posting another piece of code here.
User avatar
Jackolantern
Posts: 10893
Joined: Wed Jul 01, 2009 11:00 pm

Re: Using PHP variables on Javascript Function

Post by Jackolantern »

You can call me a hypocrite, as I have done it in many scripts I have posted to here, but I must admit I do not like generating Javascript with PHP. It just feels so hacked together, hard to read, error-prone, and is a maintenance nightmare. Of course, that is more aimed at generating Javascript that is doing operations, conditions, etc. Obviously sometimes it is in your best interest to deliver something from PHP to the client-side for Javascript. For those cases, I suggest separating out your PHP generation from the main JS to keep the JS clean. This can be done in a clean way, by making a separate area to grab the PHP variables:

Code: Select all

echo '<script type="text/javascript">';
echo "var username = ".$user['name'].";";
echo "var level = ".$user['level'].";";

/*
now that you have these values collected at the top of your script section, 
you can leverage PHP heredoc format to write clean, straight Javascript
*/

$jsScript = <<<ENDSCRIPT
//Now we can write JS freely and it will be stored in jsScript!
//  sample JS script pasted in just to show how easy heredoc format makes it
//  these comments will even be a part of the JS script ;)

function userid_validation(uid,mx,my)  
{
   var uid_len = uid.value.length; 
   if (uid_len == 0 || uid_len >= my || uid_len < mx) 
   {
       alert("User Id should not be empty / length be between "+mx+" to "+my);
       uid.focus();
       return false; 
    }
    return true;
}
ENDSCRIPT;

echo $jsScript;
 
Some may at first be sitting there blinking at the heredoc format, but I can assure you that echoing out blocks of Javascript is really just what heredoc was created for. You create a PHP variable, use the <<< operator and then type an "ending token", which is totally arbitrary and can be anything (just make sure it isn't something you will naturally use in the JS). Then, after you have typed all the JS you want to store into the variable, you just type out the ending token again with a semi-colon, and you are out of the heredoc block and you have all that text stored in the variable (in the case above, in the $jsScript variable).

You can manually echo out some variable assignments at the top of the page concatenated with the PHP variable values, and then simply use them in the heredoc'd Javascript right below it (which I did not use the variables here, since I just copy'n'pasted this script from a website to use as an example).

I know this doesn't really focus in on the main problem at hand here, but I hope this can help some people down the line with managing dynamic Javascript blocks! 8-)
The indelible lord of tl;dr
User avatar
vitinho444
Posts: 2825
Joined: Mon Mar 21, 2011 4:54 pm

Re: Using PHP variables on Javascript Function

Post by vitinho444 »

@OldRod

I tested, still nothing
I tried echoing the div and it works but it stays in before the map and then if i mouseover a village the map become bugged..
How can i undisplay the div when its mouseout and display it when its mouse over but without damaging the map?

Here's the present code:

Code: Select all

echo "<div id='tooltip'></div>";
    echo "<a class='village' onmouseover=\"tooltip('$village[nome]');\" onmouseout=\"exit();\" href='village.php?x=" . $village['x'] . "&y=". $village['y'] ."' style='top: " . $villageTop . "px; left: " . $villageLeft . "px;  padding-left:7px; padding-top:10px; padding-bottom:7px; padding-right:10px;'></a>";
    
*The tooltip css div is placed and working well.

@Jacko
Well thanks, but i think that's too hardcore for me :$ Thank you for sharing though



@edit

I got it working not the fancier way but i think i can work with it. I putted the div tooltip inside another div i placed on the side of the map, it was itentionaly for advertise but what the heck i dont need all pages with ads xD

I think i can work with this for now.

I want to say thank you all and remember that everyone who replied will be personally credited.
Thank you

@EDIT 2
Hey, i forgot something.
I decided to supply the javascript function all the information i want to show.
So i made
function tooltip(name, x, y, owner)

but how can i make new lines on the div tooltip
the current tooltip function on javascript is using innerhtml.

Code: Select all

function tooltip(tip, x, y, owner)
{
    if(!document.getElementById('tooltip')) newelement('tooltip');
    var lixlpixel_tooltip = document.getElementById('tooltip');
    lixlpixel_tooltip.innerHTML = tip;
    lixlpixel_tooltip.style.display = 'block';
    document.onmousemove = getmouseposition;
}
My Company Website: http://www.oryzhon.com

Skype: vpegas1234
Post Reply

Return to “Advanced Help and Support”