1

I have some data that I get from MySQL and I want to put it into a vue.js data property so that I can iterate over it with v-for.

What format should I choose (json or array?) and what do I have to do so that the data is available in vue.js?

<?php
  $sql = 'SELECT * FROM kurse;';
  $result = mysqli_query($conn, $sql);
  $resultCheck = mysqli_num_rows($result);

  if($resultCheck > 0) {

    $termineObj = new stdClass();
    while ($row = mysqli_fetch_assoc($result)) {

      echo $termineObj->datum = $row['datum'];
      $termineObj->uhrzeitvon = $row['uhrzeitvon'];
      $termineObj->uhrzeitbis = $row['uhrzeitbis'];
      $termineObj->freieplaetze = $row['freieplaetze'];

      $termine = json_encode($termineObj);
      echo $termine;
    }
  }
?>

...


<script>var app4 = new Vue({
  el: '#app-4',
  data: {
    termine: termine,
    },
  delimiters: ["((","))"],
  methods: {
    flipstate:function(){
      console.log('flipped');
    }
  },
})</script>

1 Answer 1

2

First, you should use json_encode() on the PHP side in order to convert your data array into an array that javascript can use.

Second, you have two options for actually using it:

a) place the JSON-encoded array/object directly into the data attribute you want, e.g.

<?php
    $data = array();
    //parse query results, insert into $data
?>

<script>
    var app4 = new Vue({
        el: '#app-4',
        data: {
            target_attr: <?=json_encode($data)?>
        },
        . . .
    });
</script>

b) Use an ajax call to insert the data from JSON, e.g.

Your PHP file

<?php
    $data = array();
    //parse query results, insert into $data
    echo json_encode(array('returned_data'=>$data));
?>

Your Javascript

<script>
    var app4 = new Vue({
        el: '#app-4',
        data: {
            target_attr: [] //or {} if you are expecting an object
        },
        mounted: {
            var vue_instance = this;
            //using jQuery for simplicity
            $.post('/path/to/your/php/file', {some: 'data if needed'}, function(data) {
                var obj = $.parseJSON(data);
                vue_instance.target_attr = obj.returned_data;
            });
        },
        . . .
    });
</script>

Getting the actual code you will need for everything to work will be left as an exercise, but I hope this pushes you in the right direction. Good luck!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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