SethCodes
SethCodes

Reputation: 283

from mysql to javascript variable

Looking for a simple solution here, I have looked around but nothing seems to give me a simple solution. I want to get data FROM my mysql database and then into my javascript variables.

These two var items in my .js file named test.js and this file is called into my .html file.

var tag_name = 'example';
var client_id = '123456789';

In a .php file called call.php I use this method (PDO) to get the required data from MySQL:

$stmt = $db->query('SELECT * FROM data WHERE id=1');
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$tag_name = $row['tag_name']; 
$client_id = $row['client_id'];
}

I want to try and achieve something along the lines of this in the .js file test.js - this obviously wont work but hopefully sheds some light on what I am trying to achieve:

var tag_name = '<?php echo $tag_name ?>';
var client_id = '<?php echo $client_id ?>';

Can I do this using an Ajax method? In my research I read that I need to use JSON? If the question has been asked before, please direct me to a post that is not just someone dumping 50+ lines of code.

Upvotes: 1

Views: 10623

Answers (3)

scotty
scotty

Reputation: 559

You can echo out your php variables as JSON and then consume them, but if you're just trying to set your js variables with data from php you might want to simply pass the variables in through a function call. Adding something like this to your php script to activate the Javascript you're trying to use for the page.

<script type="text/javascript">
    setVariables('<?php echo $tag_name ?>', '<?php echo $client_id ?>');
</script>

and then creating that function in your .js file to utilize those values and do what you need.

function setVariables(name, id){
    var tag_name = name
    var client_id = id
    //Operations that need these values.
}

Upvotes: 1

Patrick Evans
Patrick Evans

Reputation: 42736

create a php script that will generate your js and instead of linking your script tag to the .js file link it to the php script that generates the js

PHP

<?php
//mysql stuff up here
header('Content-Type: text/javascript');
?>
//some js here 
var tag_name = '<?php echo $tag_name ?>';
var client_id = '<?php echo $client_id ?>';
// some more js here

HTML

<script type="text/javascript" src="http://example.com/test.js.php"></script>

Upvotes: 2

Frantisek
Frantisek

Reputation: 7693

Here you go:

The javascript part:

$.ajax({
   url: 'call.php',
   dataType: 'json'
}).done(
   function(data){
     var tag_name = data[0];
     var client_id = data[1];
   }
);

The call.php file:

$stmt = $db->query('SELECT * FROM data WHERE id=1');
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$tag_name = $row['tag_name']; 
$client_id = $row['client_id'];
}
echo json_encode(array($tag_name,$client_id));

Upvotes: 6

Related Questions