jQuerybeast
jQuerybeast

Reputation: 14490

Use data retrieved from MySQL in JavaScript?

I am selecting some data from my database and I can echo it with PHP in my document. How can I straight pass it to JavaScript, or it its not duable, how do people deal with these things?

Here is how I get and echo:

$q=mysql_real_escape_string($_GET['q']);
$query="SELECT * FROM contacts WHERE id = '".$q."'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
    echo "Name: " . $row['first'] . " <br />";
    echo "Surname: " . $row['last'] . " <br />";
}
mysql_close();

Upvotes: 1

Views: 377

Answers (3)

user1173922
user1173922

Reputation: 111

$x is a string (or anything else really, just make sure the types are compatible before passing them)

$x = phpvar

echo "<script type='text/javascript'>
function Javascript_function(){
var passed = ".$x."}</script>";

That should do it. Don't forget the script <> tags, SO wouldn't let me insert them probably to prevent me just throwing javascript on every page.

Upvotes: 0

CLo
CLo

Reputation: 3730

This is a quick and simple way to get this setup.

echo("<script>");
echo("var myJSvar = " . json_encode($row) . ";");
echo("</script>");

Then in any JS from there you can use myJSvar;

alert(myJSvar['first'] + " " + myJSvar['last']);

Upvotes: 2

cetver
cetver

Reputation: 11829

<div id="name">
<?php echo $name; ?>
</div>

<script type="text/javascript">
//jquery example
$(document).ready(function(){
    alert($('#name').text());
});
</script>

Upvotes: 0

Related Questions