3

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?

5
  • It depends. Is the javascript being loaded in the page of that PHP code? Or is it ajax? Commented Jan 18, 2018 at 17:36
  • json_encode my friend... jay-son-en-code.... php.net/manual/en/function.json-encode.php Commented Jan 18, 2018 at 17:36
  • Also I hope this was just a typo Chmesitry ;) Commented Jan 18, 2018 at 17:38
  • 1
    @FirstOne, yes, the javascript is being loaded in this page Commented Jan 18, 2018 at 17:39
  • @IncredibleHat, eh, it is a typo Commented Jan 18, 2018 at 17:40

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

8 Comments

You don't need to run JSON.parse here. In fact it'll cause an error if you do.
Are you sure? json_encode returns a string and that string needs to be parsed into the subs object as an array...
@DanielH. It's easy to test: run both and check the generated source code / console. (I'm not iainn)
To add to @iainn's comment: it's not a string cause there is no quotes surrounding it. The generated json will be output in raw as javascript source code, which is (roughly) how you define objects in javascript.
Oh!! damn I am dense.
|

Your Answer

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.