I use this (im may contain errors in this form, but you'll get impression what i'm trying to do) to connect and fetch all data from my db. But...
How to merge (force to work together) this php file, and javascript file, where this json will be used?
Does data var would magicaaly jump to other js file included in index file?
Should i include javascript and php files in index AFTER proper html code, or BEFORE, or it just doesn't matter?
Do you know other ways to send db data from php connection to javascript file?
<?php
parseJsonToJs();
function parseJsonToJs(){
try
{
$pdo = new PDO('mysql:host=localhost;dbname=sklep_db', 'root', '');
$sth = $pdo->prepare("SELECT nazwa, logo FROM sklep");
$sth->execute();
$result = $sth->fetchAll(); /* bez PDO::FETCH_NUM */
$json=json_encode($result);
?>
<script src="app-display.js"></script>
<script type="text/javascript">
$(document).ready(function(){
<?php echo 'var data = '.$json; ?>
console.log(data);
};
</script>
<?php
echo 'dziala';
}
catch(PDOException $e)
{
echo 'nie dziala, error: ' . $e->getMessage();
}
}
?>
1 Answer 1
Do you know other ways to send db data from php connection to javascript file?
The nicest way would be to include the php-code in a separate file. In the javascript make an AJAX-call to you php-service and ask for the data, something like this.
The javascript (note that I use jQuery here):
$.ajax({
type: 'POST',
url: 'myFile.php',
success: function(result) {
var jsonData = JSON.parse(result);
// do something with the jsonData
}
});
The php
<?php
$dbh = new PDO('mysql:host=localhost;dbname=dbname', 'user', 'password');
$dbh->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, 1);
$stmt = $dbh->prepare('SELECT * FROM myTable');
$stmt->execute();
$result = $stmt->fetchAll();
$json=json_encode($result);
echo $json;
?>