Ian Nato
Ian Nato

Reputation: 1037

vue js ajax call cannot read property 'push' of undefined

I am having problems with vue.js when it comes to pushing data from the database to the webpage. I am using laravel 5.3 which converts data to Jason. the code posts to the server the number of records to be fetched then the server response with the data in which i want to display on the webpage. here is Vue js Code

new Vue({
        el: "#projects",
        data: {

            count: 0,
            fetched_projects: []
}

 methods:{
       checkproject: function(){
            var fetch = this.count += 4;               

           axios.post('/loadmore', {fetch: fetch })
               .then(function(response) {

                  this.fetched_projects.push(response.data);

               })
               .catch(function(error){
                   console.log(error);
               });

       }

HTML

 <div class="row">
    <div class="col-md-3">
        <ul v-for="more_projects in fetched_projects">
            <li>@{{ more_projects }}</li>

        </ul>

    </div>
</div>

Laravel controller

 public function setloadMore(Request $request){

  $new_projects = $request->fetch;

  $results = Model1::with('relation')->take($new_projects)->get();

  return $results;


}

The problem is on this.fetched_projects.push(response.data); its giving me "cannot read property 'push' of undifined"

Upvotes: 1

Views: 1877

Answers (2)

Jatin Marwah
Jatin Marwah

Reputation: 84

you are having "this" problem, try defining something like var that = this where you have defined fetch, and use that in place of this inside the post it should work.

Upvotes: 0

CD..
CD..

Reputation: 74096

You'd want this to be your component, so use an arrow function:

 methods:{
   checkproject: function(){
        var fetch = this.count += 4;               

       axios.post('/loadmore', {fetch: fetch })
           .then(response => {
              this.fetched_projects.push(response.data);
           })
           .catch(function(error){
               console.log(error);
           });

   }

Upvotes: 2

Related Questions