Transferring information from MySQL to Vue.js data attribute

I have retrieved some data from MySQL and I am looking to integrate it into a vue.js data property for seamless iteration using v-for.

What is the ideal format to use (JSON or array) and how can I ensure that the data is properly accessible in vue.js?

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

  if($resultCheck > 0) {

    $coursesArray = array();
    while ($row = mysqli_fetch_assoc($result)) {

      $courseObj = new stdClass();
      $courseObj->date = $row['date'];
      $courseObj->startTime = $row['start_time'];
      $courseObj->endTime = $row['end_time'];
      $courseObj->availableSeats = $row['seats'];

      array_push($coursesArray, $courseObj);      
    }
    echo json_encode($coursesArray);
  }

?>

...


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

Answer №1

Initially, it is important to utilize json_encode() on the PHP side to convert your data array into a format that can be utilized by javascript.

Next, there are two approaches you can take to implement it:

a) Embed the JSON-encoded array/object directly into the desired data attribute, for example:

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

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

b) Utilize an ajax call to insert the data from JSON, as shown below:

Your PHP script

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

Your Javascript code

<script>
    var app4 = new Vue({
        el: '#app-4',
        data: {
            target_attr: [] //or {} if 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>

Determining the specific code required for everything to function correctly is up to you, but I trust this guidance sets you on the right path. Best of luck!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Combine an array of objects using the main key in each object

I have an array of objects with different years and details var worksSummaryDetailsArr = [ { year: 2020, worksSummaryDetailsObj: [ [Object], [Object], [Object], [Object] ] }, { year: 2021, worksSummaryDetailsObj: [ [Object], [Object], ...

NodeJS experiencing a hitch in the image upload process

I am currently working on a Node code snippet that is used for uploading images. The images I am dealing with have sizes ranging from 10 to 200K, so they are relatively small in size. However, the issue I am facing is that Node seems to get stuck process ...

Fix a typing issue with TypeScript on a coding assistant

I'm struggling with typing a helper function. I need to replace null values in an object with empty strings while preserving the key-value relationships in typescript // from { name: string | undefined url: string | null | undefined icon: ...

Angular template src variable issue with no solution in sight

The videoSrc variable is not evaluating correctly images/{{videoSrc}}.mp4 When I write just videoSrc, it works fine. But when I concatenate it with other strings, it doesn't work. Check out this jsfiddle ...

Is it possible to quickly sync API data with a CSV file for updates?

My unique code allows retrieving Amazon product prices with the ASIN (Amazon Standard Identification Number). Here is the code snippet for reference. <?php class AmazonAPI { // Code implementation details here } ?> To display the price, use ...

Having trouble with the CKEditor character count function in JavaScript?

I integrated the Javascript and stylesheet from this source into my webpage. http://jsfiddle.net/VagrantRadio/2Jzpr/ However, the character countdown is not appearing on my site. What mistake have I made? ...

Could one harness the power of SO's script for adding color to code within questions?

Similar Question: Syntax highlighting code with Javascript I've observed that Stack Overflow utilizes a script to apply color coding to any code shared in questions and answers, making it resemble how it would appear in an IDE. Is this script pub ...

Learning about the functions Promise.all and Array.map()

My current project involves retrieving data from multiple APIs and aggregating them into a final array that will be displayed in the UI using React. Let me explain the scenario. First, I retrieve the main data from the primary API: const response = await ...

How can I retrieve input value using v-on:change and click events in Vue.js?

Currently, I am working on a project within vuejs: template : <b-form-input placeholder="name" type="text" class="d-inline-block" v-model="name" v-on:change="changeInput" /> <b-butt ...

What is the reason behind the unnecessary requirement of adding {...props} when passing them to a component in a React router?

Recently, I delved into learning React and encountered a puzzling issue while following a course. To gain clarity, I decided to experiment with it separately, but the confusion remains unresolved. While researching, I discovered that when utilizing a Rout ...

Selenium in C#: Timeout issue with SendKeys and Error thrown by JS Executor

Attempting to insert the large amount of data into the "Textarea1" control, I have tried two different methods. The first method successfully inserts the data but occasionally throws a timeout error, while the second method results in a JavaScript error. A ...

transferring information from Facebook to a web address through ZAPIER

Looking for guidance on sending data from Zapier to FB lead fetch. Is there a direct way to do this or is an external PHP file necessary? I need to extract name and email and send it to my CRM that is not supported by Zapier, but can receive data through U ...

Discovering the method for retrieving post parameters in Node.js

I am currently utilizing Node.js with Express and the httpAsyncClient library in Android. I have sent a request to Express using Post, including parameters. The request goes through successfully, but I am unable to retrieve the parameter in Post. I have ...

What steps can be taken to prompt the layout to transition?

I have an element that sticks to the top based on the current scroll offset. The issue is that the layout doesn't update when there is space available after the stuck element. This creates a ghost gap where the stuck element used to be... http://fidd ...

Is it possible to retrieve the BrowserWindow by its unique identifier in Electron?

Imagine if the following function is called multiple times to instantiate BrowserWindow, specifically 5 times. let mainWindow; function createWindow() { "use strict"; mainWindow = new BrowserWindow({ height: height, width: width ...

Obtain GPS coordinates (latitude/longitude) from a Google map by dropping a marker on the

Is there a straightforward script that can load a Google Map and, when clicked, display a marker that saves the latitude and longitude values to a variable? Does anyone know if there is an existing PHP solution for this functionality? Appreciate any help ...

The initial click event for the input element in Jquery is not functioning correctly

I found a jQuery date selector online and the script looked something like this... <script type="text/javascript> $(document).ready(function () { $("#date3").click(function() { $("#date3").scroller({ preset: 'datetime' }); wheels = []; whe ...

Using Selenium to assign properties to JavaScript Objects

I have a JavaScript Object that needs to be set using Selenium WebDriver. var examplePlayResponse = { "prizeIndex" : 1, "mode" : "NORMAL", "id" : "abc123", "version" : "1.0", "gameCode" : "xyz789", "randomSeed" ...

The Vue / Firebase App is experiencing issues with the Modal feature due to a lack of definition for '$'

I encountered the following error: 33:7 error '$' is not defined The code snippet below shows AddToCart.js contents. The modal formatting can be found in my Product List component. <template> <div class="add-to-cart"> ...

Transform Objects Array from AJAX Response into a Distinct JSON Entity

I am encountering a problem with a sample endpoint that is returning [object Object] for JSON data, and I can't figure out why. Mock API Initially, my code was a bit confusing, but fortunately, I found a clearer solution in another answer. functio ...