Vuejs form submit not working - javascript

I want to submit the values in my form but each time I press the submit button I get the following error:
Uncaught TypeError: login is not a function
at Object.submit [as fn] (eval at Yr (vue.min.js:7), <anonymous>:2:369)
at HTMLFormElement.<anonymous> (vue.min.js:6)
In my HTML code I have my form declared as such: <form v-on:submit.prevent="login">
In the JS it looks like this:
// register
Vue.component("login-form",
{
template: // THE HTML FORM
,
data: function () {
return data;
},
ready: function () {
this.isAuthenticated = this.checkIfAuthenticated();
this.userName = localStorage.getItem("id_name");
},
methods: {
checkIfAuthenticated: function () {
const users = [
{
id: 1,
name: "tom"
},
{
id: 2,
name: "brian"
},
{
id: 3,
name: "sam"
}
];
this.$set("users", users);
},
login: function () {
const headers = { "Content-Type": "application/x-www-form-urlencoded" };
$.ajax({
url: "/token",
type: "post",
data: `username=${this.login.username}&password=${this.login.password}`,
headers: headers,
success: function (data) {
console.info(data);
},
error: function() {
this.isValid = false;
}
});
}
}
});
// create a root instance
var vue = new Vue({
el: "#loginForm"
});
As you see the login function is in my methods, so I don't see why vue is throwing the error
Edit: inluced a JSFiddle. The problem happens when you submit the form (after you click on login)

Looks like your instance has a conflict. There is a login property in a component and there is a login method in Vue instance. Try to use different names. Issue at vuejs github:
Both data properties and methods will be set on the instance, so the
short answered is: don't use conflicting names :)

Related

Powerbi embed settings in javascriptfile dosent work?

Hope someone can help me. I have embedded a Power BI solution, and it work so fine, but when i try to hide the filter pane or apply a filter, it dosen't work. My javascript file is here:
$(function () {
var models = window["powerbi-client"].models;
var reportContainer = $("#report-container").get(0);
// Initialize iframe for embedding report
powerbi.bootstrap(reportContainer, { type: "report" });
$.ajax({
type: "GET",
url: "/embedinfo/getembedinfo",
success: function (data) {
embedData = $.parseJSON(data);
reportLoadConfig = {
type: "report",
tokenType: models.TokenType.Embed,
accessToken: embedData.EmbedToken.Token,
// You can embed different reports as per your need
embedUrl: embedData.EmbedReport[0].EmbedUrl,
permissions: permissions,
settings: {
panes: {
filters: {
visible: false
},
pageNavigation: {
visible: false
}
}
}
// Enable this setting to remove gray shoulders from embedded report
// settings: {
// background: models.BackgroundType.Transparent
// }
};
and it looks still:
What's wrong with my code?
I find and use this, and it works:
// ---- Embed Code ----------------------------------------------------
$(function () {
var models = window["powerbi-client"].models;
var reportContainer = $("#report-container").get(0);
// Initialize iframe for embedding report
powerbi.bootstrap(reportContainer, { type: "report" });
$.ajax({
type: "GET",
url: "/embedinfo/getembedinfo",
success: function (data) {
embedData = $.parseJSON(data);
var models = window["powerbi-client"].models;
// Read embed application token from textbox
var txtAccessToken = embedData.EmbedToken.Token;
// Read embed URL from textbox
var txtEmbedUrl = embedData.EmbedReport[0].EmbedUrl;
// Read embed type from radio
var tokenType = models.TokenType.Embed;
// Get models. models contains enums that can be used.
var models = window["powerbi-client"].models;
// We give All permissions to demonstrate switching between View and Edit mode and saving report.
var permissions = models.Permissions.All;
// Embed configuration used to describe the what and how to embed.
// This object is used when calling powerbi.embed.
// This also includes settings and options such as filters.
// You can find more information at https://github.com/Microsoft/PowerBI-JavaScript/wiki/Embed-Configuration-Details.
const myFilter = {
$schema: "http://powerbi.com/product/schema#advanced",
target: {
table: "myTable",
column: "myColumn",
},
operator: "In",
values: ["1"],
};
var config = {
type: "report",
tokenType: tokenType,
accessToken: txtAccessToken,
embedUrl: txtEmbedUrl,
permissions: permissions,
filters: [myFilter],
settings: {
panes: {
filters: {
visible: true,
},
pageNavigation: {
visible: true,
},
},
},
};
// Get a reference to the embedded report HTML element
var reportContainer = $("#report-container").get(0);
// Embed the report and display it within the div container.
var report = powerbi.embed(reportContainer, config);
// Report.off removes a given event handler if it exists.
report.off("loaded");
// Report.on will add an event handler which prints to Log window.
report.on("loaded", function () {
Log.logText("Loaded");
});
// Report.off removes a given event handler if it exists.
report.off("rendered");
// Report.on will add an event handler which prints to Log window.
report.on("rendered", function () {
Log.logText("Rendered");
});
report.on("error", function (event) {
Log.log(event.detail);
report.off("error");
});
report.off("saved");
report.on("saved", function (event) {
Log.log(event.detail);
if (event.detail.saveAs) {
Log.logText(
"In order to interact with the new report, create a new token and load the new report"
);
}
});
},
});
});

Laravel 5.5 + Vue.js 2.x Proper API requests

I am working locally on a Laravel 5.5 project which uses Vue.js 2.5.9 on with XAMP Server.
I have to load some information to the DOM and refresh it when click "Refresh" button.
Sometimes the information is loaded and well displayed but sometimes they are not (some of the responses are):
Error 429: { "message": "Too Many Attempts." }
Error 500: { "message": "Server Error." }
I managed to "solve" the first issue (error 429) by increasing the Middleware throttle in Kernel.php from 'throttle:60,1', to 100,1)
But the second error I am not sure why I am get it sometimes and sometimes not.
I have this in my APIController (for example):
public function users()
{
$users = User::all();
return response()->json($users);
}
Then in app.js I call the methods in the created hook like this:
const app = new Vue({
el: '#app',
data: {
...
totalUsers: 0,
...
},
created: function() {
...
this.loadUsers();
...
},
methods: {
...
loadUsers: function() {
axios.get('/api/admin/users')
.then(function (response) {
app.totalUsers = response.data.length;
});
},
refreshData: function() {
this.loadUsers():
},
...
}
});
Maybe should I replace $users = User::all() to $users = User::count() to avoid loading "too much data" in API requests?
I think you should be using mounted() instead of created() in your vue.
const app = new Vue({
el: '#app',
data: {
...
totalUsers: 0,
...
},
mounted: function() {
...
this.loadUsers();
...
},
methods: {
...
loadUsers: function() {
axios.get('/api/admin/users')
.then(function (response) {
app.totalUsers = response.data.length;
});
},
refreshData: function() {
this.loadUsers():
},
...
}
});
that's the equivalent of the $(document).on(ready) in jQuery. Thats the method that fires when the window has fully loaded.
On a side note, Laravel knows when it is returning json as an ajax response, so you could probably just amend you controller method to this
public function users()
{
return User::all();
}

got property undefined when fetching data in ajax using vue.js

I have got a undefined when I alert the param fetching from ajax using vue.js, here is my code.
test.json return:
[
{isActive: false,name: test}
]
js:
new Vue({
el: '#viewport',
data: {
test_data: []
},
mounted: function () {
this.fetchTestData();
},
methods: {
fetchTestData: function () {
$.get(test.json, function (data) {
this.test_data = data;
alert(this.test_data.isActive);
});
}
}
});
I am beginner of vue.js, hope have a reply, thanks.
If you are fetching this data from that test.json file,
first it need to be like that because that's not validate json:
[
{
"isActive": false,
"name": "test"
}
]
and you need to use bind because this not referring to the Vue instance
fetchTestData: function () {
$.get('test.json', function (data) {
this.test_data = data;
alert(this.test_data[0].isActive);
}.bind(this));
}
and accessing the data like that this.test_data[0].isActive because it's an array

Meteor fetch on client undefined outside of helper

I am trying to fetch an entry in a collection with:
client/views/home.js:
criticalCrewNumber = ConfigValues.find({
name: 'criticalCrewNumber'
}).fetch()[0].value;
But I'm getting error:
Uncaught TypeError: Cannot read property 'value' of undefined
If I run the code in the browser console, the desired value is returned as a string.
I have tried various things, e.g. using findOne; placing the code elsewhere in the app; using iron-router waitOn for the subscription to come, etc. Every attempt so far has failed as I end up with undefined.
Here's how the collection is defined, published and subscribed to:
lib/config/admin_config.js:
ConfigValues = new Mongo.Collection("configValues");
ConfigValues.attachSchema(new SimpleSchema({
name: {
type: String,
label: "Name",
max: 200
},
value: {
type: String,
label: "Value",
max: 200
}
}));
both/collections/eventsCollection.js:
if (Meteor.isClient) {
Meteor.subscribe('events');
Meteor.subscribe('config');
};
server/lib/collections.js
```
Meteor.publish('events', function () {
return Events.find();
});
Meteor.publish('config', function () {
return ConfigValues.find();
});
```
Does anyone know what's going on? Thanks.
Consider using ReactiveVar (and Meteor.subscribe callbacks):
criticalCrewNumber = new ReactiveVar();
Meteor.subscribe('config', {
onReady: function () {
var config = ConfigValues.findOne({name: 'criticalCrewNumber'});
if (config) {
criticalCrewNumber.set(config.value);
} else {
console.error('No config value.');
}
},
onStop: function (error) {
if (error) {
console.error(error);
}
}
});

Emberjs authentication session not working

I have followed Authentication Tutorial, but running into some issues.
I have a php backend api which resides in another domain, http://rest.api {local development}
The ember js application uses ember-app-kit and connects to the rest api.
When the user submits the login form it sends the username/email with password to one of the route defined in the rest api Session Controller
import AuthManager from 'lms/config/auth_manager';
var SessionNewController = Ember.ObjectController.extend({
attemptedTransition : null,
loginText : 'Log In',
actions: {
loginUser : function() {
var self = this;
var router = this.get('target');
var data = this.getProperties('identity', 'password');
var attemptedTrans = this.get('attemptedTransition');
$.post('http://rest.api/login',
data,
function(results) {
console.log(results.session);
console.log(results.user_id);
AuthManager.authenticate(results.session, results.user_id);
if(attemptedTrans) {
attemptedTrans.retry();
self.set('attemptedTransition', null);
} else {
router.transitionTo('index');
}
}
)
}
}
});
export default SessionNewController;
After receiving the api result in the results variable which looks like this :
Object {success: "user login success", session: "2OmwKLPclC.YhYAT3745467my7t0m2uo", user_id: "1"}
But as soon as I capture the data and send it to the AuthManager which resides in Auth Manager Code
import User from 'lms/models/user';
import Application from 'lms/adapters/application';
var AuthManager = Ember.Object.extend({
init: function() {
this._super();
var accessToken = $.cookie('access_token');
var authUserId = $.cookie('auth_user');
if(!Ember.isEmpty(accessToken) || !Ember.isEmpty(authUserId)) {
this.authenticate(accessToken, authUserId);
}
},
isAuthenticated: function() {
return !Ember.isEmpty(this.get('ApiKey.accessToken')) && !Ember.isEmpty(this.get('ApiKey.user'));
},
authenticate: function(accessToken, userId) {
$.ajaxSetup({
headers: { 'Authorization': 'Bearer ' + accessToken }
});
var user = User.store.find(userId);
console.log(user);
this.set('ApiKey', ApiKey.create({
accessToken: accessToken,
user: user
}));
},
reset: function() {
this.set('ApiKey', null);
$.ajaxSetup({
headers: { 'Authorization': 'Bearer None' }
});
},
apiKeyObserver: function() {
Application.accessToken = this.get('apikey.accessToken');
if (Ember.isEmpty(this.get('ApiKey'))) {
$.removeCookie('access_token');
$.removeCookie('auth_user');
} else {
$.cookie('access_token', this.get('ApiKey.accessToken'));
$.cookie('auth_user', this.get('ApiKey.user.id'));
}
}.observes('ApiKey')
});
export default AuthManager;
I got an error in the console saying
Uncaught TypeError: Object function () {
if (!wasApplied) {
Class.proto(); // prepare prototype...
}
o_defineProperty(this, GUID_KEY, undefinedDescriptor);
o_defineProperty(this, '_super', undefinedDescriptor);
var m = met...<omitted>...e' new.js:23
(anonymous function) new.js:23
jQuery.Callbacks.fire jquery.js:1037
jQuery.Callbacks.self.fireWith jquery.js:1148
done jquery.js:8074
jQuery.ajaxTransport.send.callback jquery.js:8598
It is not able to pass the variables to the imported function.
Finally got this working. The error that was I doing is after extending the Ember.Object.extend() on auth_manager.js, I didn't create the object anywhere. Thats why it couldnt set create a cookie and throwing that error message.
All I had to do was, .create() after extending the object.
Don't know whether it is the right method or not. But it certainly works.

Categories

Resources