Search code examples
ajaxlaravelvue.jsvue-resource

ajax call with vuejs


Im trying to get data from an endpoint api/data which passes an object. But when I run my app I dont see anything in my console and in the network tab I dont see any xhr request. There is no warning and errors in console too. Am I doing anything wrong here? I have checked the endpoint and its passing data from backend properly.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>FLashy</title>
    <link rel="stylesheet" href="http://localhost:8000/css/bootstrap.min.css" media="screen" title="no title">

  </head>
  <body>

    <div class="container">
        <div class="row">
          <div class="col-md-4 col-md-offset-4" id="app">
            <h3 class="Text center">Datas</h3>
             <p>
              @{{ datas }}
             </p>
          </div>
       </div>
    </div>

    <!-- scripts -->
    <script src="http://localhost:8000/js/jquery-2.2.4.min.js"></script>
    <script src="http://localhost:8000/js/bootstrap.min.js" charset="utf-8"></script>
    <script src="http://localhost:8000/js/vue.js" charset="utf-8"></script>
    <script src="http://localhost:8000/js/vue-resource.min.js" charset="utf-8"></script>

<script type="text/javascript">

  new Vue({
           el:  '#app',

         data: {

         },

      methods:{

      fetchData: function(){
          this.$http.get('api/data').then(function(response){

                // this.$set('datas', response.data);
                console.log(response);
          }, function(response){
              // error callback
          });
      },

          ready: function(){
            this.fetchData();
        }
      }
  });
</script>
  </body>
</html>

web.php

Route::get('api/data', function(){
  $a = [];
  $a['id'] = 1;
  $a['message'] = 'Lorem ipsum dolor sit amet, consectetur';
  $a['status'] = 'Completed';
  return response()->json($a,200);
});

Solution

  • Your ready hook is inside methods: {} handler but in reality should be outside:

    methods: {
      fetchData: function () {
        // your AJAX here
      }
    },
    ready: function () {
      this.fetchData()
    }