Skip to content
Advertisement

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;
        }
      });
  },

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement