0

I am writing code to get data from MySQL database and using Vuejs,

this.$http.get("api.php?action=read")
        .then(response => {
          console.log(response);
        }, error => {
          console.log(error);
        });

this request returns all api.php content and doesn't return the data.

here is the api.php file

<?php

  require_once('include/config.php');

  $res = (['error' => false]);

  $action = 'read';

  if (isset($_GET['action'])) {
    $action = $_GET['action'];
  }

  if($action == 'read') {
      $images = array();

      $query = 'SELECT * FROM images ORDER BY id DESC';
      $select_images = mysqli_query($connection, $query);
      while($image = mysqli_fetch_assoc($select_images)) {
        array_push($images, $image);
      }
      echo json_encode($images);
  }

  mysqli_close($connection);
  header("Content-type: application/json");
  echo json_encode($images);
  die();
?>

Can anyone help me, Please?

3 Answers 3

1

It works,

I added

header("Access-Control-Allow-Origin: *");

to the API file

and make the get request from the localhost/vuejs link, not like localhost:8080 and it's work

Thanks

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

Comments

1

Include the header in the php. Note: should be the 1st line before you return anything.

<?php
header("Access-Control-Allow-Origin: *");

And try to run the php code 1st using command prompt:

php -S localhost:8888 ajaxfile.php

Note: try to use different port number as for me it is unable to get the api from same 8080 port in which my vueProject is running. This will create an api end point with your php. Which will listen to http://localhost:8888/projectname/api.php.

Now When used axios.get(http://localhost:8888/projectname/api.php) will get the response for the api.I havent tried without axios module but i guess it should work.

allRecords: function(){
  axios.get('http://localhost:8888/VueAxios/ajaxfile.php').then(response => {
    this.users = response.data
    console.log(response.data)
  })
  .catch(function (error) {
    console.log(error);
  });
}

This function worked for me. Note: axios is a very handy in this situation. Hope it helps.

Comments

0

Try response.body to get the response data:

this.$http.get("api.php?action=read")
        .then(response => {
          console.log(response.body);
        }, error => {
          console.log(error);
        });

2 Comments

@MahmoudEl-halaq What does the output of console.log(response) look like?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.