How to display this using Vue.js? [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
{ message: "Hello how are you", status: false, state: Kerala }
The following values are the response of an AJAX request. Each time the response changes. I need to print it using Vue.js?
<script>
regBox = new Vue({
el: "#regBox",
data: {
username : '',
},
methods: {
handelSubmit: function(e) {
data = {};
data['username'] = this.username;
$.ajax({
url: 'https://herokuapp.com/api/user/box/',
data: data,
type: "POST",
dataType: 'json',
success: function(e) {
if (e.status) {
alert(" Success")
} else {
alert("failed");
}
}
});
return false;
}
},
});
</script>

Example #1: just one response at a time
regBox = new Vue({
el: "#regBox",
data: {
username : '',
response: {
message: '',
status: '',
state: ''
}
},
methods: {
handelSubmit: function(e) {
var vm = this; // so you can access "this" inside jquery success
data = {};
data['username'] = this.username;
$.ajax({
url: 'https://herokuapp.com/api/user/box/',
data: data,
type: "POST",
dataType: 'json',
success: function(e) {
vm.response = e;
}
});
return false;
}
},
});
example template:
<div id="regBox">
<div v-if="response.message" class="{ 'alert-success': response.status, 'alert-danger': !response.status}">
<p>{{ response.message }}</p>
</div>
</div>
Example #2: multiple responses at a time:
regBox = new Vue({
el: "#regBox",
data: {
username : '',
responses: []
},
methods: {
handelSubmit: function(e) {
data = {};
data['username'] = this.username;
$.ajax({
url: 'https://herokuapp.com/api/user/box/',
data: data,
type: "POST",
dataType: 'json',
success: function(e) {
// like this to prevent all items to be binded, they would otherwise change whenever you get a new response.
vm.responses.push({
message: e.message,
status: e.status,
state: e.state
});
}
});
return false;
}
},
});
example template:
<div id="regBox">
<div class="{ 'alert-success': response.status, 'alert-danger': !response.status}" v-for="response in responses">
<p>{{ response.message }}</p>
</div>
</div>
afterwards, you can also use setTimeout if you want to remove the response after some time.

I see from the $.ajax that you are mixing vue.js with jquery, which should be avoided whenever possible. You can use a different library for your AJAX request, such as axios.
Here is an explanation for using axios with vue.js:
https://alligator.io/vuejs/rest-api-axios/

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

How to display following response using vue js?

This is my response.. How to display the error message? passwords do not match
{"errors": {"password": ["Passwords donot match"]}, "status": false, "msg": "Validation erro", "error-type": 0}
Currently my code is
<script>
regBox = new Vue({
el: "#regBox",
data: {
..........
response: {
message: '',
status: '',
state: '',
errors: '',
}
},
methods: {
handelSubmit: function(e) {
var vm = this;
data = {};
..............
$.ajax({
url: '',
data: data,
type: "POST",
dataType: 'json',
success: function(e) {
if (e.status)
{
alert(" Success")
}
else {
vm.response = e;
alert(" Failed")
}
}
});
return false;
}
},
});
</script>
My html code to display the same is
<p class="error">{{response.errors.password}}</p>
Currently i am getting error message as
["Passwords donot match"]
How to get only message as
Passwords donot match.. so, how can i able to get it.. can anybody help
This should work:
<p class="error">{{response.errors.password[0]}}</p>
Get the first element
<p class="error">{{response.errors.password[0]}}</p>

Mvc Jquery Ajax Funtion Not Working [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Can not Work function for ajax,can I work ? I want to show a notification with mvc ajax..But I use ActionResult comeback Return RedirectToAction("myAction","myControl"),Can I make.
Thanks for help ..
My Sample Code:
$(document).ready(function () {
$.ajax({
url: '/Kategori/KategoriEkle',
type: 'POST',
data: "{}",
datatype: 'html',
success: function () {
var unique_id = $.gritter.add({
title: 'Welcome to Home!',
text: 'Message',
//image: '/assets/img/ui-sam.jpg',
sticky: true,
time: '',
class_name: 'my-sticky-class'
});
return false;
}
});
});
Kategori.cs
[HttpPost]
public ActionResult KategoriEkle(Kategori kategori)
{
KutuphaneContext db = new KutuphaneContext();
var con = db.Kategori.Where(x => x.KategoriAdi == kategori.KategoriAdi).Count();
if (con <= 0 && kategori.KategoriAdi != null)
{
_kategoriRepository.Insert(kategori);
_kategoriRepository.Save();
}
return RedirectToAction("Kategoriler", "Kategori");
}
}
This may help you out. Redirect in Ajax call method instead of controller
In controller return Json
[HttpPost]
public ActionResult KategoriEkle(Kategori kategori)
{
KutuphaneContext db = new KutuphaneContext();
var con = db.Kategori.Where(x => x.KategoriAdi == kategori.KategoriAdi).Count();
if (con <= 0 && kategori.KategoriAdi != null)
{
_kategoriRepository.Insert(kategori);
_kategoriRepository.Save();
}
url = Url.Action("Kategoriler", "Kategori");
redirect = true;
return Json(new
{
redirectUrl = url,
isRedirect = redirect
}, JsonRequestBehavior.AllowGet);
}
In Ajax Call
$.ajax({
url: '/Kategori/KategoriEkle',
type: 'POST',
data: "{}",
datatype: 'json',
contentType: "application/json; charset=utf-8",
success: function () {
var unique_id = $.gritter.add({
title: 'Welcome to Home!',
text: 'Message',
//image: '/assets/img/ui-sam.jpg',
sticky: true,
time: '',
class_name: 'my-sticky-class'
if (response.isRedirect) {
window.location.href = response.redirectUrl;
return false;
}
else {
alert('Error occurred.');
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}

Vue.js 2: Get data from AJAX method

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.

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;
}
});
}

Categories

Resources