1

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();
 }
 }
 ?>
RiggsFolly
94.7k22 gold badges108 silver badges152 bronze badges
asked Aug 8, 2014 at 7:35

1 Answer 1

5

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;
?>
answered Aug 8, 2014 at 8:03
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you dude. I hope STB (stalker middleware) can use ajax, but we'll see :) Cheers!
Can you help me out? I got an error from the line "$.ajax({" : "Uncaught ReferenceError: $ is not defined". Can it be possible, that on WAMP server ajax/jquery is not working?
Are you sure you have included a jQuery reference? Also make sure that you include jQuery before you run any scripts that requires jQuery. AJAX/jQuery should work on WAMP so it has nothing to do with that.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.