[Vuejs]-VueJS – Post array of object using jquery $.ajax

0👍

Like @Kalimah said, this here refers to the ajax function and not the Vue instance. It’s the same when using Axios. Try putting this in a var outside of the ajax function so that it can refer to the parent object:

saveData: function() {
    const self = this;
    $.ajax({
        url: "/api/links", 
        method:"post", 
        data: JSON.stringify(self.results), // Replace 'this' with self'' 
        contentType: 'application/json',
        dataType: 'json',
        context: this,
        success: function(res) {
            $("#res").html(res);
        }
    });
}

Here’s a small example to illustrate the issue. In this case, the parent object is the window object, but in your case, it will be the Vue instance:

(function() {
    const self = this;
    const thisEl = document.querySelector('.this')
    const selfEl = document.querySelector('.self')
    $.ajax({
        url: "/", 
        beforeSend: function(res) {
            thisEl.innerText = this
            selfEl.innerText = self
        },
    });
})()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3 class="this"></h3>
<h3 class="self"></h3>

Leave a comment