Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save results from pdo query to a javascript variable

Tags:

javascript

php

I am new to javascript so please be patient with me. I have a function in php which goes like this:

 public function getSubjects() {
            $stmt = $this->_db->prepare('SELECT id, subject from subjects');
            $stmt->execute();                     
            return  $stmt->fetchall();
        }

Then I have a variable subs in javascript which is hardocded like this:

var subs = {"Maths":1,"Geography":2,"Chmesitry":3,"Literature":4};

How do I populate the subs variable with the format above from the getSubjects method?

like image 567
Dani M Avatar asked May 28 '26 02:05

Dani M


1 Answers

I like to use json_encode to convert the array to json so it can be used as an array of objects in JS.

PHP:

public function getSubjects() {
    $stmt = $this->_db->prepare('SELECT id, subject from subjects');
    $stmt->execute();                     
    return json_encode($stmt->fetchall());
}

In javascript:

var subs = <?php echo getSubjects(); ?>;
console.log(subs);
like image 77
Daniel H. Avatar answered May 30 '26 15:05

Daniel H.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!