Mithun Sudheendran
Mithun Sudheendran

Reputation: 27

Pass a database value to JavaScript

I retrieved all of my friends' names which are currently online using MySQL joins and PHP.

Now I want to insert their names inside JavaScript for chatting with them.

<a href="javascript:void(0)" onclick="javascript:chatWith('Friend1')">Friend1 </a>
<a href="javascript:void(0)" onclick="javascript:chatWith('Friend2')">Friend2 </a>

I am unable to do this. Because I don't know how to call JavaScript inside PHP or viceversa.

while($get_usernames=mysql_fetch_array($get_users_query)) {             
    echo '<br>'.$get_usernames['username'];                         
}

I want to show each of $get_usernames['username'] as Friend1, Friend2, inside JavaScript

Upvotes: 0

Views: 2075

Answers (3)

chrisblomm
chrisblomm

Reputation: 314

Something like:

<?php
$aUsernames = array();
while($get_usernames=mysql_fetch_array($get_users_query)) {             
    array_push($aUsernames, $get_usernames['username']);                         
}
foreach($aUsernames as $name) {
?>
<a href="javascript:void(0)" onclick="javascript:chatWith('<?php echo $name; ?>')"><?= $name; ?> </a>
<?php
}
?>

Using AJAX is much neater ofcourse, but this will suffice if it is all in one PHP file.

Also I would like to encourage you to move to PDO or Mysqli since mysql functions are deprecated.

Upvotes: 0

Blunderfest
Blunderfest

Reputation: 1854

If you want to place some PHP variable inside javascript, a simple way of doing it is by simply using the php loop inside your page to create the a tags.

Something like this:

$aTagList = "";
while($get_usernames=mysql_fetch_array($get_users_query)) {             
    $aTagList .= "<a href='javascript:void(0)' onclick='javascript:chatWith(\"".$get_usernames['username']."\")>".$get_usernames['username']."</a>";                         
}

Then echo the $aTagList wherever you need it in the page with some inline code.

<?php echo $aTagList; ?>

Not sure if I got all the escaping correct, but it should give you the right idea.

Upvotes: 1

Hari krishnan
Hari krishnan

Reputation: 2108

You can use AJAX to call a php page and get value from that.

Call the php page and after querying simply return value using echo. You can get that value using responseText in javascript

http://www.tizag.com/ajaxTutorial/ajaxphp.php

Upvotes: 2

Related Questions