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
Related
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 1 year ago.
I am trying to create an array of User IDs to send in an AJAX Post Request. I can get the User IDs okay and display them individually in console.log but after I push them to the connectionData array and try to do a console.log on specific indices I get undefined, also when I try console.log(connectionData.length) it returns 0. I believe this is a sync issue but I can't figure out how to solve it, I have read similar posts and they aren't helping.
const prepareUserDataForConnection = function(){
var connectionData = [];
var currentUser = 'robert';
var currentUser = 'chris';
console.log(currentUser);
console.log(followedUser);
$.ajax({
type: 'GET',
url: '/api/currentuserinfo/',
data: {
'current_user': currentUser
},
success: function(data) {
let currentUserId = JSON.stringify(data[0].id);
console.log('Current User Pk is: ' + currentUserId);
connectionData.push(currentUserId);
},
});
$.ajax({
type: 'GET',
url: '/api/followeduserinfo/',
data: {
'followed_user': followedUser
},
success: function(data) {
let followedUserId = JSON.stringify(data[0].id);
console.log('Followed User Pk is: ' + followedUserId);
connectionData.push(followedUserId);
},
});
console.log(connectionData)
console.log(connectionData[0])
console.log("Array length is: " + connectionData.length)
};
Here is a screenshot of the problem:
Try this approach with Promise
function ajaxPromise(obj) {
return new Promise(function (resolve, reject) {
obj.success = resolve;
obj.error = reject;
$.ajax(obj);
});
}
const prepareUserDataForConnection = function () {
var currentUser = 'robert';
var followedUser = 'chris';
return Promise.all([
ajaxPromise({
type: 'GET',
url: '/api/currentuserinfo/',
data: { 'current_user': currentUser }
}),
ajaxPromise({
type: 'GET',
url: '/api/followeduserinfo/',
data: { 'followed_user': followedUser }
})
]);
};
prepareUserDataForConnection().then(function (connectionData) {
console.log(connectionData)
console.log(connectionData[0])
console.log("Array length is: " + connectionData.length)
// Write your logic here with connectionData
}).catch(function (error) {
console.log(error);
});
After sending the localStorage to server the const arrayOrders is showing up as empty even it contains values in client side.
I've tried to do that with this way but it not works.
Here is my code from server side and client side for requests handle.
What's wrong?
In server side :
exports.wip = functions.https.onRequest((req, res) => {
cors(req, res, () => {
const url = `${req.protocol}://${req.get('host')}/work-in-process`;
const tokenId = req.get('Authorization').split('Bearer ')[1];
const arrayOrders = req.headers['service']; // {}
const wipReq = JSON.stringify({
operator: req.body.uid,
conditions: req.body.status,
service_list: {
orders: [arrayOrders]
}
})
return admin.auth().verifyIdToken(tokenId)
.then((decoded) => {res.redirect(302, url.href)})
.catch((err) => res.status(401).send(err));
});
});
In client side :
$(function() {
'a long time ago user recorded a' localStorage.setItem("service_array", array);
$('.SubForm').on('submit', function(e) {
$.ajax({
type: 'post',
url: 'http://localhost:3000/wip',
data: $(this).serialize(),
success: function(data) {
if (data.status) {
$.ajax({
type: 'get',
url: 'http://localhost:3000/wip',
beforeSend: function(xhr) {
xhr.setRequestHeader('service', localStorage.getItem("service_array"));
},
success: location.href = "http://localhost:3000/wip"
})
}
}
});
e.preventDefault();
});
});
Storage objects are simple key-value stores, similar to objects, but they stay intact through page loads. The keys and the values are always strings (note that, as with objects, integer keys will be automatically converted to strings). You can access these values like an object, or with the Storage.getItem() and Storage.setItem() methods.
From: https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API
So storing an array in localStorage may have mixed results. I would suggest:
$(function() {
var data = [];
var storeData = JSON.stringify(data);
localStorage.setItem("service_array", storeData);
$('.SubForm').on('submit', function(e) {
$.ajax({
type: 'post',
url: 'http://localhost:3000/wip',
data: $(this).serialize(),
success: function(data) {
if (data.status) {
$.ajax({
type: 'get',
url: 'http://localhost:3000/wip',
beforeSend: function(xhr) {
xhr.setRequestHeader('service', localStorage.getItem("service_array"));
},
success: function(){
location.href = "http://localhost:3000/wip";
}
});
}
}
});
e.preventDefault();
});
});
It was not clear from your example where array was defined. Basically, you can use JSON.stringify() or $.param() to convert the Array data into String that can be stored to localStorage. Depending on your needs, you can convert it when you get the String back into an Array.
Hope that helps.
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.
I have scenario that first onload page i put data into one pouchdb and with same pouchdb with other event of click it have to go server and fetch data in same pouch but it create two id ,but i need is second time it have into same pouch with first time create id how can i do this??
out put:
first time:
ressss---->:{"rows":[{"value":{"existing":[{"pattano":1843,"surveyNo":"156 ","subdivNo":"3B","ownerDetails":[{"relNo":1,"ownerNo":1,"RelationCode":"3","status":"Existing","udsRatio":"0","MaxOwnNumb":"1","relation":"மகள்","owner":"த்ஃப்க்","surveyNo":"156 ","statofown":"E","relative":"த்ஃப்க்","subDivNo":"3B"}]}],"_id":"6163ED1A-B1E8-4A90-8EEF-BF4B1A1E6132","_rev":"1-dea5c55e64c7543a26f24192ec5e94a5"}}]}
second time:
ressss---->:{"rows":[{"value":{"existing":[{"pattano":1843,"surveyNo":"156 ","subdivNo":"3B","ownerDetails":[{"relNo":1,"ownerNo":1,"RelationCode":"3","status":"Existing","udsRatio":"0","MaxOwnNumb":"1","relation":"மகள்","owner":"த்ஃப்க்","surveyNo":"156 ","statofown":"E","relative":"த்ஃப்க்","subDivNo":"3B"}]}],"_id":"6163ED1A-B1E8-4A90-8EEF-BF4B1A1E6132","_rev":"1-dea5c55e64c7543a26f24192ec5e94a5"}},{"value":{"existing":[{"pattano":457,"surveyNo":"111","subdivNo":"4","ownerDetails":[{"relNo":2,"ownerNo":1,"RelationCode":"1","status":"Existing","udsRatio":"0","MaxOwnNumb":"4","relation":"மகன்","owner":"மணிவேல்","surveyNo":"111","statofown":"E","relative":"ஆலப்பன்","subDivNo":"4"}]}],"_id":"E421B84D-2481-4ED1-ABDD-0C0B24BAEB91","_rev":"4-6713d5be5336f69b0f6c776b5c343d49"}}]}
my function is:
function fetchOwners(existingOwnersObj)
{
//alert("in fetch owners");
var inputVal = JSON.stringify(existingOwnersObj);
//alert("inputVal===> "+inputVal);
var hash1 = cal_hmac(inputVal);
var m = "";
document.getElementById('imgdiv')
.style.display = 'block';
$
.ajax(
{
url: urlService + serviceName + '/getPattaOwnersforJoint?jsoncallback=?',
headers:
{
"emp_value": ses,
"signature": hash,
"roleId": roleId,
"timestamp": t,
},
type: 'POST',
dataType: 'jsonp',
data: inputVal.toString(),
// jsonpCallback:"aaa",
contentType: "application/json",
success: function(data)
{
// alert("im in success===>"+JSON.stringify(data));
existown = {};
existown.existing = data;
//existown.slNno=slNno++;
str = JSON.stringify(existown);
//alert("str----->"+str);
var str1 = JSON.parse(str);
//new Pouch('idb://tamilNilamExist', function(err, db)
Pouch(puch, function(err, db)
{
var doc = existown;
db.put(doc, function(err, doc)
{
if (err)
{
return console.error(err);
}
else
{
//alert("Data Locally Stored Successfully adkkdd exizthhh");
$("#imgdiv")
.hide();
}
});
});
// getexist();
//
},
error: function(jqXHR, exception)
{
// alert("Error:"+JSON.stringify(jqXHR));
alert("Error Occured");
document.getElementById('imgdiv')
.style.display = 'none';
}
});
}
It looks like you are using a very old version of PouchDB. If you update to 3.4.0, you should be able to easily do something like:
// only need to instantiate the PouchDB once
var db = new PouchDB('mydb');
// inside of asynchronous functions, just call the db directly
function asyncSomething() {
function asyncSomethingElse() {
db.put(...)
}
}
I have a User model:
var UserModel = Backbone.Model.extend({
defaults: {
handle: '',
email: '',
uuid: '',
userpic: '',
tokenlogin: ''
}
});
I also have a collection called UserSignIn, although I'm not sure why:
var UserSignIn = Backbone.Collection.extend({ model: UserModel });
And inside of my SignInView view, I have the following function...
signIn: function(e) {
e.preventDefault();
this.collection.fetch({
type: 'POST',
url: 'http://localhost/app/api/User.php',
dataType: "json",
data: $.param({
req: "REQUSERSIGNIN",
platform: "WEB",
useremail: $('#userSignIn #userEmail').val(),
userpass: $('#userSignIn #userPassword').val()
}),
success: function(data) {
// In here, I'd like to create an
// instance of the model which I'd
// like to pass around my app.
var user = new UserModel({
handle: data.HANDLE,
email: data.EMAIL,
uuid: data.UUIDUSER,
userpic: data.USERPIC,
tokenlogin: data.TOKENLOGIN
});
}
});
}
As you can see, all I am trying to do is create an instance of a User on success of the BackBone.fetch() function.
I'd like to understand how to then pass around this new "user" UserModel() instance around my app. When I try to console.log(user) I get a "ReferenceError: user is not defined" when clearly I just created it in the success callback of the fetch function.
Can someone explain to me why?
you have to insert it into your collection if you wanna follow the right way in backbone.
I think that you can do this:
into your initialize in the view insert this:
initialize: function(){
//..... your code in initialize
this.userModel = null;
this.collection = new UserCollection();
},
signIn: function(e) {
e.preventDefault();
var here = this;
this.collection.fetch({
type: 'POST',
url: 'http://localhost/app/api/User.php',
dataType: "json",
data: $.param({
req: "REQUSERSIGNIN",
platform: "WEB",
useremail: $('#userSignIn #userEmail').val(),
userpass: $('#userSignIn #userPassword').val()
}),
success: function(data) {
var user = {handle: data.HANDLE,email: data.EMAIL,uuid: data.UUIDUSER,userpic: data.USERPIC,tokenlogin: data.TOKENLOGIN};
here.userModel = new UserModel(user);
here.collection.addUser(here.userModel);
}
});
}
You UserCollection must be something like this:
var UserCollection = Backbone.Collection.extend({
model: UserModel,
initialize:function(){
console.log('Initialized User collection');
},
addUser: function(users, options) {
return this.add(users, options);
}
});
To console each element of your collection you can try this (if you run this code inside your success function use here instead of this):
this.collection.each(function(user, index) {
console.log(user);
//if you want to set a value of your model:
user.set('email', 'yournewemail#email.it');
//if you want to get some value
user.get('email');
});
The variable user is scoped only to within the success function of your SignInView view, so you can't console.log(user) which is looking for a user variable from the global scope. You could put console.log(user) right after creating the user within the success function to see that it is created, since this would find the local variable user.
To access it from the app, you could also declare var user; outside the fetch function and then simply set it within the fetch function.