Ajax JSON obj to HTML template Using Vue JS

by John H
6 minutes

I wanted to take a simple results set from a database using php, return that result set back as a JSON object, then fetch that result using Jquery's ajax method, then load those results to a webpage using Vue.js.  I could have just used Jquery to append some html  - but I wanted to use Vue since I could make a more complex template, plus it might afford me some other future options, and I wanted to do it!

This tutorial involves all the parts necessary for getting the app up and running.

Mysql Table Create syntax

CREATE TABLE `test` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `url` varchar(100) DEFAULT NULL,
  `site` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

INSERT INTO `test` (`id`, `url`, `site`)
VALUES
    (1,'http://www.google.com','Google'),
    (2,'http://www.bing.com','Bing'),
    (3,'http://www.yahoo.com','Yahoo'),
    (4,'http://www.johnharbison.net','JohnHarbison.net'),
    (5,'http://www.watchinformer.com','Watchinformer.com');

PHP service

<?php 
  // Configure database connector
  define( 'DB_HOST', 'localhost' );
  define( 'DB_USER', 'root' );
  define( 'DB_PWD', 'root' );
  define( 'DB_NAME', 'test' );  

/////////////

  // Connect to database
  $Link = mysqli_connect(DB_HOST, DB_USER, DB_PWD, DB_NAME);
  if ( !$Link ) {
    echo "Under Maintenance";
    exit();  
  }

  //RETURN ARRAY OF RECORDS
  function getRecords() {
    Global $Link;
    $sql = "SELECT id, url, site FROM `test`";
  $results = mysqli_query($Link, $sql );

    if (!$results) { echo mysqli_error($Link); echo ' 
' .  $sql; }

    $rowsAll = [];
      while ($row = $results->fetch_assoc()) {
          $rowsAll[] = $row;
    }
    return $rowsAll;
  }

// IF AJAX POST - SEND RECORDS
if ($_POST['get_records']) {
    $allRecords = getRecords();
    echo json_encode($allRecords);
    die();
}

  // THEN A THE END OF THE FILE
  mysqli_close($Link);
?>

The way the php works is that a Mysql connection is made to my local mysql instance. If a post call is made to the page then it will return all the records and encode them to json. If there isn't a post then it doesn't do anything.

Vue App


<html>
    <head>
        <title> Service to Display 
        <style>

        
    <!-- PRODUCTION vue.js framework 
        -->
        <!-- DEV VUE -->
    <script src="https://unpkg.com/vue@2.5.13/dist/vue.js">
    <!-- include the jquery for ajax calls -->
    <script src="https://code.jquery.com/jquery-3.2.1.js">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">
    </head>
    <body>

 <div id="app"> 
  <!-- TEMPLATE CONTAINER -->
  <div class="container">
    <component :is="currentView" :posts="thePosts" transition="fade" transition-mode="out-in">
  </div>
</div>

<template id="manage-template">
  <div>
  <h3>Sites
  </h3> 
    <table class="table">
      <tr>
          <th>ID
          <th>Url 
          <th> Site
      </tr>
      <tr  v-for="post in posts"> 
        <td>
         {{ post.id }}
        </td>
        <td>
           <a v-bind:href="post.url" target="_blank"> {{ post.url }} 
        </td>
        <td>
          {{ post.site }}
        </td>
      </tr>
   </table>
 </div>
</template>

<script>
 Vue.component('manage-posts', {
    template: '#manage-template',
    props: ['posts'],
  })

  var vm = new Vue({
    el: '#app',
    mounted: function() { 
      this.getRecords()
    },
    data: {
      currentView: 'manage-posts',
      thePosts: ''
    },
    methods: {
      getRecords: function() {
        jQuery.ajax({
              method: "POST",
              url: '',
              data: {'get_records': true},
              dataType: "JSON"
            }).done(function(resp){
              vm.thePosts = resp;
            });
      } // end getRecords
    }// end methods
  })
</script>

    </body>
</html>

When I was developing this I had the php and the vue app all in the same file and ran it as a php file.

About the file

I included Vue.js, Bootstrap CSS, and JQuery - to handle the ajax call.

The app contains a component called manage-template. The component has a prop called posts. The vm (Vue instance) has a data property called thePosts which is initially set to an empty string. There is a method in the vm called getRecords which makes the ajax call - the method is post and it sends a parameter called get_records which is set to true. The php when it sees the POST call and get_records parameter it will send out the JSON object with the Mysql results. When the vm.getRecords method is successful it sets the vm.thePosts property equal to the JSON obj response. The Vue component assigns :posts="thePosts" which then passes that variable into the template (manage-template). There is a table in the template that uses the v-for loop in a set of table rows (tr). It is relatively straight forward and has been stripped down to its basics.

Github Repo

I've made a repo that contains this and a few other vue.js examples. https://github.com/john-harbison/vue-examples. This specific file is called vue-service-to-display.php

Related Articles

Ways to Motivate Users

I'm constantly thinking about ways to instigate use. I think that ultimately comes from my...

John H John H
8 minutes

Javascript InnerHTML Table Issues with AJAX

If you need to use Javascript innerHTML to update an element on the page you may run into issues...

John H John H
~1 minute

Simple HTML content fade in with JQuery

JQuery in the Head $( document ).ready(function() {...

John H John H
2 minutes