'How do I call a php file with axios?

I am doing a CRUD with vue.js and php. I installed the axios and I believe it is working. I just don't know how to call the php file that connects to the database and creates, read ...

The folder structure:

enter image description here

An excerpt from my script:

<script>
 import axios from 'axios';
 export default {
 name: "HelloWorld",
 data() {
   return{
     showAddModal: false,
     showEditModal: false,
     showDeleteModal: false,
     errorMsg: "",
     successMsg: "",
     projects: [],
     newProject: {
       title: "",
     },
     currentProject: {},
  }
},
created: function () {
  this.getAllProjects();
},
methods: {
  getAllProjects: function () {
    axios
      .get("../php/action.php?action=read")
      .then(function (response) {
        if (response.data.error) {
          this.errorMsg = response.data.message;
        } else {
          this.projects = response.data.projects;
        }
      });
  },


Solution 1:[1]

In axios you are referencing a file which will not work

methods: {
  getAllProjects: function () {
    axios
      .get("../php/action.php?action=read") // This will not work
      .then(function (response) {
        if (response.data.error) {
          this.errorMsg = response.data.message;
        } else {
          this.projects = response.data.projects;
        }
      });
  },

Axios makes http requests meaning it needs to be calling a server. You will need to have the PHP file running on some sort of server to be able to call it from axios

methods: {
  getAllProjects: function () {
    axios
      .get("http://localhost:8000/some-url") // This will work
      .then(function (response) {
        if (response.data.error) {
          this.errorMsg = response.data.message;
        } else {
          this.projects = response.data.projects;
        }
      });
  },

If working with windows, look into WAMP, if working in OSX look into MAMP

These are two simple PHP servers you can configure

Solution 2:[2]

Hey I think this is the best solution as it (for me) works locally and when running in production!

this.axios.get(`/thef_file_you_want_to_get/execute.php?, //query-params...
               function (req, res) {
                    // for testing cors...
                    // res.header("Access-Control-Allow-Origin", "*");
               }

              ).then(function (response) {
                console.log(response);
            })

By removing the origin, 'http(s)://localhost:3000' for example, the request will happen to the current domain. 'yourwebsite.com' => https://yourwebsite.com /thef_file_you_want_to_get/execute.php? for example.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Devin Gray
Solution 2 Marko Miletic