Vue.js 2: Get data from AJAX method - javascript

I'm new to Vue, and I'm attempting to grab the data via AJAX in a method.
I know the method is working.
Here's the Vue code:
Vue.component('sub-folder', {
props: ['folder'],
template: '{{folder.title}}'
});
var buildFoldersList = new Vue({
el: '#sub-folders',
data: {
foldersList: this.foldersList
},
methods: {
buildFolders: function () {
$.ajax({
url: base_url + 'api/folder/get_subfolders/' + browser_folder_id,
method: 'POST',
data: {
"folder_id": browser_folder_id
},
success: function (data) {
console.log("Data");
console.log(data);
this.foldersList = data;
},
error: function (error) {
alert(JSON.stringify(error));
}
});
}
}
});
Here's the HTML:
<div class="list-group" id="sub-folders">
<sub-folder v-for="folder in foldersList" :key="folder.folder_id" v-bind:folder="folder"></sub-folder>
</div>
At the moment, the containing template is running, but since the method isn't getting executed, there's no data.
I've tried everything I know to trigger the method, but I've run out of ideas.

It seems you are not calling the buildFolders method at all, you can call it from the created hook of vue.js like following:
var buildFoldersList = new Vue({
el: '#sub-folders',
data: {
foldersList: []
},
created () {
this.buildFolders()
},
methods: {
buildFolders: function () {
var self = this
$.ajax({
url: base_url + 'api/folder/get_subfolders/' + browser_folder_id,
method: 'POST',
data: {
"folder_id": browser_folder_id
},
success: function (data) {
console.log("Data");
console.log(data);
self.foldersList = data;
},
error: function (error) {
alert(JSON.stringify(error));
}
});
}
}
});
Also you can relook at how you are using this, as scope of this will change in $.ajax method as happened here, see the explanation here.

Related

How to save data in Vue instance

The question is quite simple,
All I want is to get the data after the AJAX post saved in Vue instace's data.
Here is my code:
const VMList = new Vue({
el: '#MODAL_USER_DATA',
data: {
user: []//,
//userAcc: []
},
methods: {
getUserAcc: function ( userID ) {
this.user = { _id : userID };
var self = this
$.ajax({
url: "/listuser",
type: "POST",
data: this.user,
success: function(data) {
this.user = data ;
//this.userAcc = Object.assign({}, this.userAcc, data );
alert(JSON.stringify(this.user));//show the user correctly (e.g user = data)
$('#popupDeleteModal').modal('show');
alert(JSON.stringify(data));//show data,the entire json object,everything is good
},
error: function(err) {
console.log('error: ',err);
},
});
}
}
});
And after I trigger the getUserAcc(id) method,I try to verify the VMList.user value in browser console,and I get only the id.Seems like after the function is over the data is reset.How could I store the data from the AJAX post request in the user object from data:{...} ?
Thank you for help!!!
The problem is that this inside your ajax return function doesn't refer to the vue instance anymore.
The solution is to save the this keyword into a variable inside the function. Example:
getUserAcc: function ( userID ) {
var that = this;
this.user = { _id : userID };
$.ajax({
url: "/listuser",
type: "POST",
data: this.user,
success: function(data) {
that.user = data;
//Rest of your code
},
error: function(err) {
console.log('error: ',err);
},
});
}
Here is more information about the behavior of the keyword this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

Fetch data with Vue from Web API

I have a Web API and I'm trying to get JSON Data from it by using Vue, but I get neither data or errors, so I don't what is wrong. I want to load the data when the page is loaded.
Here is my code:
const v = new Vue({
el: '#divContent',
ready: function () {
this.loadData();
},
data: {
content: 'loading',
serverData: null
},
methods: {
loadData: function (viewerUserId, posterUserId) {
const that = this;
$.ajax({
contentType: "application/json",
dataType: "json",
url: "http://my-webapi/",
method: "Post",
success: function (response) {
that.$data.serverData = response;
},
error: function () {
alert('Error')
}
});
}
}
});
My HTML
<div id="divContent" class="content">
{{ content }}
</div>
Yes you can use jQuery’s $.ajax() API. However, using jQuery just for making Ajax calls is not recommended. You don’t want to include the whole jQuery library just for the purpose of using Ajax, do you? :-)
For Vue.js, you have quite a few options for using Ajax, such as:
Axios
vue-resource
Browser's built-in fetch API (Using fetch)
Here is an example of using the Browser's fetch API.
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.16/dist/vue.js"></script>
</head>
<body>
<div id="divContent">
<h1>Article Search Results</h1>
<form v-on:submit.prevent="search">
<input type="text" v-model="query">
<button type="submit">Search</button>
</form>
<ul>
<li v-for="article in articles" v-bind:key="article.source + article.id">
{{ article.title }}
</li>
</ul>
</div>
</body>
</html>
JavaScript
const vm = new Vue({
el: '#divContent',
data() {
return {
query: 'gene',
articles: 'loading'
}
},
created() {
this.search();
},
methods: {
search: function () {
fetch(`https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=${this.query}&format=json`)
.then(response => response.json())
.then(json => {
this.articles = json.resultList.result;
});
}
}
});
Output
You appear to already be using jQuery, so to load the Vue when the page is loaded you can update your code to the following:
$(function(){
const v = new Vue({
el: '#divContent',
created: function () {
this.loadData();
},
data: {
content: 'loading',
serverData: null
},
methods: {
loadData: function (viewerUserId, posterUserId) {
const that = this;
$.ajax({
contentType: "application/json",
dataType: "json",
url: "http://my-webapi/",
method: "Post",
success: response => this.serverData = response,
error: err => alert('Error')
});
}
}
});
})
The syntax above is using the jQuery.ready shorthand to create the Vue only after the page is loaded.
Without jQuery, you might want to listen for the DOMContentLoaded event.
Alternatively, just load the script that creates the Vue at the bottom of the page and not in the header.
Here is a complete, working example.
console.clear()
$(function(){
const v = new Vue({
el: '#divContent',
created: function () {
this.loadData();
},
data: {
content: 'loading',
serverData: null
},
methods: {
loadData: function (viewerUserId, posterUserId) {
$.ajax({
contentType: "application/json",
dataType: "json",
url: "https://httpbin.org/post",
data: JSON.stringify({testing: "some value"}),
method: "Post",
success: response => {
this.content = "loaded"
this.serverData = response.json
},
error: err => console.log('Error')
});
}
}
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.js"></script>
<div id="divContent" class="content">
{{ content }}
<hr>
Response: <br>
{{ serverData }}
</div>
Anything your put inside methods: {} won't work
unless you call loadData() with #click on the element or when page loads.
So, you should call it on the element or using either created/mount methods:
So, in your case either do this.
<div id="divContent" class="content" #click='loadData'>
or call the method when the page loads as:
created () {
this.loadData()
}
For Loading it on the page load, you can do the following:
const v = new Vue({
el: '#divContent',
data: {
content: 'loading',
serverData: null
},
methods: {
loadData(viewerUserId, posterUserId) {
$.ajax({
contentType: "application/json",
dataType: "json",
url: "http://my-webapi/",
method: "POST",
success: function (response) {
this.content = 'loaded';
this.serverData = response;
},
error: function () {
alert('Error')
}
});
}
},
mounted() {
this.loadData()
}
});

Ajax POST don't work after button click

My problem is lack of action after pressing the button. Under the button hook AJAX function.
Please a hint where I have a bug // errors.
My code:
Controller:
[HttpPost]
public ActionResult InsertCodesToDB(string name)
{
cl.InsertCodesToDB(name);
fl.MoveCodeFileToAccept(name);
string response = "Test";
return Content(response, "application/json");
}
View / Button:
<input type="button" class="btn btn-success sendCodesToDB" value="Umieść kody w bazie" data-value="#item.Name"/>
View / Script:
<script>
$('.sendCodesToDB').on('click', function () {
var name = $(this).data("value");
$.ajax({
url: '/ActualCodes/InsertCodesToDB',
type: 'POST',
dataType: 'json',
cache: false,
data: JSON.stringify({ 'name': 'name' }),
success: function (response) {
#(ViewBag.MessageOK) = response;
},
error: function () {
onBegin;
}
});
});
function onBegin() {
$('#files').hide();
$('#insertFiles').hide();
$('#loading').show();
$('#lblSelectedProductName').text('Trwa umieszczanie kodów w bazie danych. Proszę czekać ...');
$('#ttt').show();
}
</script>
Thank you in advance for your help.
You seem to not be adding the on ready function for jQuery. Try adding it before your click action and closing it before your onBegin() function, like so:
<script>
// open here
$( document ).ready(function() {
$('.sendCodesToDB').on('click', function () {
var name = $(this).data("value");
$.ajax({
url: '/ActualCodes/InsertCodesToDB',
type: 'POST',
dataType: 'json',
cache: false,
data: JSON.stringify({ 'name': 'name' }),
success: function (response) {
#(ViewBag.MessageOK) = response;
},
error: function () {
// function call missing "()"
onBegin();
}
});
});
// and close here
});
function onBegin() {
$('#files').hide();
$('#insertFiles').hide();
$('#loading').show();
$('#lblSelectedProductName').text('Trwa umieszczanie kodów w bazie danych. Proszę czekać ...');
$('#ttt').show();
}
</script>
The code in Ajax must be JavaScript. You cannot use C# code there (except to print some values). What is #(ViewBag.MessageOK) doing here:
success: function (response) {
#(ViewBag.MessageOK) = response;
},
If you want to display the response in a message box, try something like:
success: function (response) {
$("#your_message_id").html(response);
},
Notes: aside from that, you have several errors in your code as others pointed out in the comments.
1- Remove the quotes from the data like this:
data: JSON.stringify({ name: name }),
2- Change the error to this:
error: function () {
onBegin(); // You need "()" here
}
Or better this:
error: onBegin // You don't need "()" here
I guess you are sending data inside the AJAX call in the wrong way.
Try it like this
data: JSON.stringify({ name: name })
Hope this will help you.

Changing Vue.js example to use ajax

Im using Vue.js in my latest project and in part of the project i need to render a tree view which is stored in a db - Im using the Vue.js tree view example as a base and have the data coming from my server in the correct format.
Ive found a way to modify the example to load the data from js but by the time it does, the component has already been rendered. Ive checked that the data works when I preload a var with the data from the server.
How would I change things to make this load from ajax?
My js:
Vue.component('item', {
template: '#item-template',
props: {
model: Object
},
data: function() {
return {
open: false
}
},
computed: {
isFolder: function() {
return this.model.children && this.model.children.length
}
},
methods: {
toggle: function() {
if (this.isFolder) {
this.open = !this.open
}
},
changeType: function() {
if (!this.isFolder) {
Vue.set(this.model, 'children', [])
this.addChild()
this.open = true
}
}
}
})
var demo = new Vue({
el: '#demo',
data: {
treeData: {}
},
ready: function() {
this.fetchData();
},
methods: {
fetchData: function() {
$.ajax({
url: 'http://example.com/api/categories/channel/treejson',
type: 'get',
dataType: 'json',
async: false,
success: function(data) {
var self = this;
self.treeData = data;
}
});
}
}
})
the template :
<script type="text/x-template" id="item-template">
<li>
<div
:class="{bold: isFolder}"
#click="toggle"
#dblclick="changeType">
#{{model.name}}
<span v-if="isFolder">[#{{open ? '-' : '+'}}]</span>
</div>
<ul v-show="open" v-if="isFolder">
<item
class="item"
v-for="model in model.children"
:model="model">
</item>
</ul>
</li>
</script>
And the html:
<ul id="demo">
<item
class="item"
:model="treeData">
</item>
</ul>
The problem is in the $.ajax() call. The value of self in the success handler has the wrong value
success: function(data) {
var self = this; // this = jqXHR object
self.treeData = data;
}
Either use the context option and this.treeData
$.ajax({
url: 'http://example.com/api/categories/channel/treejson',
type: 'get',
context: this, // tells jQuery to use the current context as the context of the success handler
dataType: 'json',
async: false,
success: function (data) {
this.treeData = data;
}
});
Or move the var self = this line in the correct place right before $.ajax();
fetchData: function () {
var self = this;
$.ajax({
url: 'http://example.com/api/categories/channel/treejson',
type: 'get',
dataType: 'json',
async: false,
success: function (data) {
self.treeData = data;
}
});
}

AJAX/ json returning null open cart

Hi Im attempting a simple ajax request but I keep getting a null value for json.
Here is my javascript...
<script>
$(document).ready( function() {
$('#donate-box-submit').on('click', function() {
var donate_code = $('#charity-campaign-code').val();
var donate_amount = $('#charity-campaign-amount').val();
$.ajax({
url: 'index.php?route=donate/donatenow',
type: 'post',
data: {
donate_code: donate_code,
donate_amount: donate_amount
},
dataType: 'json',
beforeSend: function() {
},
complete: function() {
},
success: function(json) {
console.log(json);
alert(json['test']);
},
error: function() {
}
});
});
});
</script>
and my php...
public function donatenow() {
$json = array(
'test' => 'Output this text'
);
$this->response->setOutput(json_encode($json));
}
I have also tried echo json_encode($json); just to rule out any issues with that OpenCart function, but the same issue is still there.
The problem is the route you are using to call the method. Not sure on exactly what class you are using as the controller, but there should be three parts to the route: route=aaa/bbb/donatenow where as you've got aaa/donatenow

Categories

Resources