I want to populate a component data using a method with Axios. However, with Axios, the component data is always undefined. If I don't use Axios (hardcode the return value), the component data populates correctly.
data () {
return {
myData: this.getData();
}
},
methods:{
getData(){
axios({
method: 'GET',
url : 'Department/GetAllForDropdown',
}).then(function (response){
return response.data;
});
}
}
How do I achieve this without using the conventional way of populating, e.g.
.then(function (response){
self.myData = response.data;
})
Thank you.
=======EDIT========
I have a dynamic form builder. I am using vuetify. It creates the form components from the data I have declared.
<template>
<div v-for="formItem in formDetails.formInfo">
<v-text-field
v-if="formItem.type != 'select'
:label="formItem.placeholder"
v-model="formItem.value"
></v-text-field>
<v-select
v-if="formItem.type == 'select'
:items="formItem.options"
:label="formItem.placeholder"
v-model="formItem.value"
></v-select>
</div>
</template>
data () {
return {
formDetails: {
title: 'myTitle',
formInfo:[
{
type:'text',
placeholder:'Name*',
value: '',
},
{
type:'select',
placeholder:'Option1*',
options: this.getOptions1(),
value: '',
},
{
type:'select',
placeholder:'Option2*',
options: this.getOptions2(),
value: '',
},
]
},
}
},
methods:{
getOptions1(){
var self = this;
axios({
method: 'GET',
url : 'Department1/GetAllForDropdown',
}).then(function (response){
return response.data;
});
},
getOptions2(){
var self = this;
axios({
method: 'GET',
url : 'Department2/GetAllForDropdown',
}).then(function (response){
return response.data;
});
}
}
I am currently stuck at making the select box dynamic, because I plan to pass in the options like
options: this.getOptions1(),
for them to get all the options in the select box.
Thank you.
The idea is still assigning the response to the item and leave a placeholder while loading.
getOptions(formItem) {
formItem.loading = true;
var placeholder = formItem.placeholder;
formItem.placeholder = "Loading... Please wait";
axios({
method: "GET",
url: "Department1/GetAllForDropdown"
}).then(function(response) {
formItem.loading = false;
formItem.placeholder = placeholder;
formItem.options = response.data;
});
}
I write a small demo. You could try it out.
Related
I try to make an cascading dropdown, but I have problems with the sending and fetching of the response data.
Backend:
[HttpPost]
public async Task<JsonResult> CascadeDropDowns(string type, int id)
{ .............
return Json(model);
}
Here I get the correct data.
First I tried:
$("#dropdown").change( function () {
var valueId = $(this).val();
var name = $(this).attr("id");
let data = new URLSearchParams();
data.append("type", name);
data.append("id", valueId);
fetch("#Url.Action("CascadeDropDowns", "Home")", {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
},
body: data
})
.then(response => {
console.log('Success:', response);
return response.json();
})
.then(json => {
console.log('Success:', json );
console.log('data:', json.Projects);
PopulateDropDown("#subdropdown1",json.Projects)
})
.catch(error => {
console.log('Error:', error);
});
});
Here I can send the Request and get a "success" back. However, when I access json.Projects I just get an `undefined. I have tried to change the Content-Type, without success.
Secondly I have used:
$.ajax({
url: "#Url.Action("CascadeDropDowns", "Home")",
data: data,
type: "POST",
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function (data) {
console.log(data);
},
error: function (r) {
console.log(r.responseText);
},
failure: function (r) {
console.log(r.responseText);
}
});
With this I get an Illegal Invocation Error.
What do I have to do that get either of those working? What are their problems?
I try to make an cascading dropdown, but I have problems with the
sending and fetching of the response data.What do I have to do that get either of those working? What are their problems?
Well, let consider the first approach, you are trying to retrieve response like json.Projects but its incorrect because data is not there and you are getting undefined as below:
Solution:
Your response would be in json instead of json.Projects
Complete Demo:
HTML:
<div class="form-group">
<label class="col-md-4 control-label">State</label>
<div class="col-md-6">
<select class="form-control" id="ddlState"></select>
<br />
</div>
</div>
Javascript:
var ddlState = $('#ddlState');
ddlState.empty();
ddlState.append($("<option></option>").val('').html('Please wait ...'));
let data = new URLSearchParams();
data.append("type", "INDIA");
data.append("id", 101);
fetch("http://localhost:5094/ReactPost/CascadeDropDowns", {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
},
body: data
})
.then(response => {
return response.json();
})
.then(result => {
console.log(result);
var ddlState = $('#ddlState');
ddlState.empty();
ddlState.append($("<option></option>").val('').html('Select State'));
$.each(result, function (index, states) {
ddlState.append($("<option></option>").val(states.cityId).html(states.cityName));
});
})
Second approach:
In ajax request you are passing object as object fahsion like data: data whereas, your controller expecting as parameter consequently, you are getting following error:
Solution:
You should pass your data within your ajax request like this way data: { type: "YourTypeValue", id:101 }, instead of data: data,
Complete Sample:
$.ajax({
url: 'http://localhost:5094/ReactPost/CascadeDropDowns',
type: 'POST',
data: { type: "YourValue", id:101 },
success: function (response) {
ddlState.empty();
ddlState.append($("<option></option>").val('').html('Select State'));
$.each(response, function (i, states) {
ddlState.append($("<option></option>").val(states.cityId).html(states.cityName));
});
},
error: function (response) {
alert('Error!');
}
});
Note: I have ommited contentType because, by default contentType is "application/x-www-form-urlencoded;charset=UTF-8" if we don't define.
Output:
I am trying to set an data from a method. I am using fetch to get an rest data. But, when I try to set the data, using this.item = 'test' doesn't work. So, when my this.item is inside ".then" doesn't working. But when is out of ".then" it working... But I need to use a rest call to get the data...
Vue.component('internal_menu', {
props: ['list'],
data: function () {
return {
item: '1'
}
},
methods: {
teste(event)
{
event.preventDefault();
var payload = {
method: 'GET',
headers: { "Accept": "application/json; odata=verbose" },
credentials: 'same-origin' // or credentials: 'include'
}
const url = _spPageContextInfo.webAbsoluteUrl +
"/_api/Web/Lists/GetByTitle('"+ this.list +"')/Items?
$select=Title,Id,Link,Icone&$orderby=Title%20asc";
fetch(url,payload)
.then((resp) => resp.json())
.then(function(data)
{
let items = data.d.results;
this.item = 'teste';// this not working here
})
. catch(function(error) {
console.log(JSON.stringify(error));
});
this.item = 'tst123'; //this working here
},
},
template: `
<div id='tst'>
<h3>{{list}} - {{item}}</h3>
<button v-on:click="teste">Try Me</button>
</div>
`,
mounted: function () {
this.getMenuData();
}
})
new Vue({
el: "#app"
})
thanks
Everton
When you do this:
.then(function(data)
{
let items = data.d.results;
this.item = 'teste';// this not working here
})
Your closure's reference to this is the within the context of the anonymous function. Instead, you need to use the fat arrow function in order to maintain the context of the Component.
.then((data) => {
let items = data.d.results;
this.item = 'test';
})
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
I have a function :
$scope.insert = function(){
var data = {
'username' : $scope.username,
'password' : $scope.password,
'nama_lengkap' : $scope.nama_lengkap
}
$http({
method: 'POST',
url: './sys/mac.php',
data : data
}).then(function(response){
return response.data;
});
}
and the function work perfectly, but i want my page change to datalist and refresh datalist after insert() true. my function insert() run in the route "localhost/learn/#!/administrator" so i want it change to route "localhost/learn/#!/" after insert() true. i used location.href='#!/' but it not work for refresh datalist automaticaly, just change location.
If you want to update an object from a service call, you can do the following. I have added an onError function too, to help with debugging.
Tip: Research adding service calls into a Service that AngularJS framework provides. It helps for writing maintainable and structured code.
$scope.objectToUpdate;
$scope.insert = function(){
var data = {
'username' : $scope.username,
'password' : $scope.password,
'nama_lengkap' : $scope.nama_lengkap
}
$http({
method: 'POST',
url: './sys/mac.php',
data : data
}).then(function(response){
$scope.objectToUpdate = response.data.d;
}, function(e){
alert(e); //catch error
});
}
Optional Service
Below is an example of how to make use of Angular Services to make server calls
app.service('dataService', function ($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function (url, data) {
// $http() returns a $promise that we can add handlers with .then() in controller
return $http({
method: 'POST',
url: './sys/' + url + '.php',
dataType: 'json',
data: data,
headers: { 'Content-Type': 'application/json; charset=utf-8' }
});
};
});
Then call this service from your controller, or any controller that injects DataService
var data = {
'username' : $scope.username,
'password' : $scope.password,
'nama_lengkap' : $scope.nama_lengkap
}
dataService.getData('mac', data).then(function (e) {
$scope.objectToUpdate = e.data.d;
}, function (error) {
alert(error);
});
I have a model that is updated based on an async call. For some reason, the UI does not get updated. Could you point me to why this might be happening. The code is below. I have verified that the code does work if I do not have an async call. I am using ember 2.0. Thank you for your help.
App.GroupsRoute = Em.Route.extend({
model: function() {
var groupsData = [];
Promise.resolve(Ember.$.ajax({
type: 'POST',
url: '/someservice.json',
contentType: 'application/json',
data: JSON.stringify({
allFor: 'group',
query: ''
})
})).then(function(data) {
groupsData = data.items;
return groupsData;
}.bind(this)).catch(function(error) {
console.log('Error retrieving devices data ' + error);
});
return groupsData;
}
});