I want to call a rest service (post) when I press on the button login but it doesn't launch any service it just add a "?" at the end of the url of my application.
here is my js :
(function ($) {
var authentication = Backbone.Model.extend({
defaults: {
Username: "",
Password: ""
},
url:'../../rest/login'
});
var LoginView = Backbone.View.extend({
model: new authentication(),
el: $("#login-form"),
events: {
"click button#login": "login"
},
login: function(){
alert("ici");
this.model.save({username: this.$el.find("#inUser")}, {
password: this.$el.find("#inPswd")}, {
success: function() {
/* update the view now */
},
error: function() {
/* handle the error code here */
}
});
}
})
})
(jQuery);
And here is my form :
<form class="form-inline">
<div class="form-group">
<input type="text" class="form-control" placeholder="Username" id="inUser"></input>
<input type="password" class="form-control" placeholder="Password" id="inPswd"></input>
<button id="login">Login</button>
</div>
</form>
You have a problem with your .save() method call because you send username and password in two different objects.
Also to stop adding question mark ? sign (stop submitting your form) you need to add event.preventDefault(); and/or return false; to your button click handler.
Here is a fix:
login: function(event) {
event.preventDefault();
alert("ici");
this.model.save({
username: this.$el.find("#inUser"),
password: this.$el.find("#inPswd")
}, {
success: function() {
/* update the view now */
},
error: function() {
/* handle the error code here */
}
});
return false;
}
Related
I am trying to redirect a user to a different page after they input there correct user information and then pressing the submit button using (window.location.href) to redirect but the page keeps reloading after the form has been submitted
<form id="login" method="post">
<h1>Login students</h1>
<label for ="username">username:</label>
<input required type="username" id="username" v-model="username">
<br><br>
<label for="password">password: </label>
<input required type="password" id="password" v-model='password'>
<br><br>
<button v-on:click='onSubmit'>submit</button>
</form>
var loginApp = new Vue({
el: '#login',
data: {
username: '',
password: '',
},
methods: {
onSubmit: function () {
// check if the email already exists
var users = '';
var newUser = this.username;
var passcheck = this.password;
if (localStorage.getItem('users')) { // 'users' is an array of objects
users = JSON.parse(localStorage.getItem('users'));
}
if (users) {
if (users.some(function (user) {
return user.username === newUser & user.password === passcheck
})) {
//alert('Welcome back-' + newUser);
//window.location.href = '<index.html>' + '' + newUser;
window.location.href = "index.html";
} else {
alert('Incorrect username or password');
}
}
}
}
});
the proble is with
<form id="login" method="post">
the form doesn't have an action defined, so it makes the browsers refresh.
you need to prevent the default action either through the form element
<form v-on:submit.prevent>
or through your onsubmit handler:
methods: {
onSubmit: function (e) {
e.preventDefault()
//...
}
}
I'm having trouble getting started with binding a Form to a remote Datasource in Kendo UI for javascript
I have verified that the ajax call returns the correct JSONP payload, e.g:
jQuery31006691693527470279_1519697653511([{"employee_id":1,"username":"Chai"}])
Below is the code:
<script type="text/javascript">
$(document).ready(function() {
var viewModel = kendo.observable({
employeeSource: new kendo.data.DataSource({
transport: {
read: {
url: baseUrl + "/temp1",
dataType: "jsonp"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {
models: kendo.stringify(options.models)
};
}
return options;
}
},
batch: true,
schema: {
model: {
id: "employee_id",
fields:{
employee_id: { type: "number" },
username: { type: "string" }
}
}
}
}),
hasChanges: false,
save: function() {
this.employeeSource.sync();
this.set("hasChanges", false);
},
change: function() {
this.set("hasChanges", true);
}
});
kendo.bind($("#item-container"), viewModel);
viewModel.employeeSource.read();
});
</script>
<div id="item-container">
<div class="row">
<div class="col-xs-6 form-group">
<label>Username</label>
<input class="form-control k-textbox" type="text" id="username" data-bind="value: username, events: { change: change }" />
</div>
</div>
<button data-bind="click: save, enabled: hasChanges" class="k-button k-primary">Submit All Changes</button>
</div>
No errors are thrown, but I was expecting my username text form field to be populated with the value 'Chai', and so on.. but it doesn't
Your textbox is bound to a username property but this doesn't exist on your view-model, nor is it being populated anywhere. Assuming your datasource correctly holds an employee after your call to read(), you will need to extract it and set it into your viewmodel using something like this:
change: function(e) {
var data = this.data();
if (data.length && data.length === 1) {
this.set("employee", data[0]);
this.set("hasChanges", true);
}
}
And modify the binding(s) like this:
<input class="form-control k-textbox" type="text" id="username"
data-bind="value: employee.username, events: { change: change }" />
You should also be aware that the change event is raised in other situations, so if you start using the datasource to make updates for example, you'll need to adapt that code to take account of the type of request. See the event documentation for more info. Hope this helps.
I am implementing a very simple React login page. I have started with the following component, Account.
var Account = React.createClass({
getInitialState: function() {
return {
showSignUp: false,
showLogin: true
}
},
update: function(data) {
this.setState(data);
},
render: function() {
if(this.state.showSignUp) {
return <SignUp/>
}
else {
return <Login update={this.update}/>
}
}
});
As expected, the Login component is displayed and renders the following:
return (
<div>
<p><input type="text" placeholder={Language.languagePack.account.username} onChange={this.usernameChange}/></p>
<p><input type="password" placeholder={Language.languagePack.account.password} onChange={this.passwordChange}/></p>
<p><a onClick={this.performLogin}>{Language.languagePack.account.login}</a></p>
<p><a onClick={this.handleSignUp}>{Language.languagePack.account.signUp}</a></p>
<p>{failedMessage}</p>
</div>
)
This all works fine. The application is picking up on the changes via the onChange hook. If the user clicks "Sign Up" though, then the following code is called:
handleSignUp: function() {
this.props.update({showSignUp: true, showLogin: false})
},
Which calls the update method in the Account class, which updates the state and causes a re-render. This is what causes it to switch to the SignUp component.
return (
<div id="signUp">
<p><input type="text" placeholder={Language.languagePack.account.username} onChange={this.usernameChange} /></p>
<p><input type="password" placeholder={Language.languagePack.account.password} onChange={this.passwordChange} /></p>
<p><input type="email" placeholder={Language.languagePack.account.email} onChange={this.emailChange} /></p>
<p><a onClick={this.handleSignUp}>{Language.languagePack.account.signUp}</a></p>
</div>
)
And for some reason, none of the events are firing on this. onChange or onClick doesn't seem to be registered. I think this is related to my implementation of switching components based on a state change that renders different components. My question is, why is this happening and what part of React have I misunderstood to make this happen?
Full Classes
Login Component
var Login = React.createClass({
getInitialState: function() {
return {
username: '',
password: '',
failed: false
}
},
usernameChange: function(event) {
this.setState({
username: event.target.value,
failed: false
});
},
passwordChange: function(event) {
this.setState({
password: event.target.value,
failed: false
});
},
performLogin: function() {
var username = this.state.username;
var password = this.state.password;
console.log("Attempting login with username " + username + " and password " + password);
var _this = this;
Api.login(username, password, function(response) {
_this.props.update({user: response, loggedIn: true});
},
function(response) {
_this.setState({failed: true});
})
},
handleSignUp: function() {
this.props.update({showSignUp: true, showLogin: false})
},
render: function() {
var failedMessage = null;
if(this.state.failed) {
failedMessage = <div className="failed-auth">{Language.languagePack.account.invalidCredentials}</div>;
}
return (
<div>
<p><input type="text" placeholder={Language.languagePack.account.username} onChange={this.usernameChange}/></p>
<p><input type="password" placeholder={Language.languagePack.account.password} onChange={this.passwordChange}/></p>
<p><a onClick={this.performLogin}>{Language.languagePack.account.login}</a></p>
<p><a onClick={this.handleSignUp}>{Language.languagePack.account.signUp}</a></p>
<p>{failedMessage}</p>
</div>
)
}
});
Signup Component
var SignUp = React.createClass({
getInitialState : function() {
return {
username: '',
password: '',
email: ''
}
},
usernameChange: function(event) {
this.setState({
username: event.target.value
});
},
passwordChange: function(event) {
this.setState({
password: event.target.value
});
},
emailChange: function(event) {
this.setState({
email: event.target.value
});
},
handleSignUp : function() {
var username = this.state.username;
var password = this.state.password;
var email = this.state.email;
console.log("Signing up with username=" + username + " and password=" + password + "and email=" + email);
},
handleLogin : function() {
console.log("Fired!");
},
render: function () {
return (
<div id="signUp">
<p><input type="text" placeholder={Language.languagePack.account.username} onChange={this.usernameChange} /></p>
<p><input type="password" placeholder={Language.languagePack.account.password} onChange={this.passwordChange} /></p>
<p><input type="email" placeholder={Language.languagePack.account.email} onChange={this.emailChange} /></p>
<p><a onClick={this.handleSignUp}>{Language.languagePack.account.signUp}</a></p>
</div>
)
}
});
Your code does work; However, I did remove references to language.LanguagePack, since that's not defined in the code you provided. If you have a javascript error, it will prevent code from running.
https://jsfiddle.net/tqz3skcr/2/
var SignUp = React.createClass({
getInitialState : function() {
return {
username: '',
password: '',
email: ''
}
},
usernameChange: function(event) {
console.log('username Changed');
this.setState({
username: event.target.value
});
},
passwordChange: function(event) {
console.log('password Changed');
this.setState({
password: event.target.value
});
},
emailChange: function(event) {
console.log('email changed');
this.setState({
email: event.target.value
});
},
handleSignUp : function() {
var username = this.state.username;
var password = this.state.password;
var email = this.state.email;
console.log("Signing up with username=" + username + " and password=" + password + "and email=" + email);
},
handleLogin : function() {
console.log("Fired!");
},
render: function () {
return (
<div id="signUp">
<p><input type="text" onChange={this.usernameChange} /></p>
<p><input type="password" onChange={this.passwordChange} /></p>
<p><input type="email" onChange={this.emailChange} /></p>
<p><a onClick={this.handleSignUp}></a></p>
</div>
)
}
});
ReactDOM.render(
<SignUp />,
document.getElementById('container')
);
I don't see anything obvious but you could try this pattern to show/hide the components. Toggle showing and hiding components in ReactJs.
First of all, make your life easier and don't use indicators like:
{
showSignUp: true,
showLogin: false
}
something like this would be much simpler and would produce less errors:
{
formToShow: "signUpForm" // or "loginForm"
}
I would say, if you start coding in this way the issue will resolve by "clean code magic" ))
I'm attempting to write a jQuery script to store an authentication token from a REST API service. I had a block of working code but decided to modularize to make the application more scalable. Now, it seems that the preventDefault portion is no longer working.
<form action="/" id="authorize">
<label for="username">Username:</label><br />
<input type="text" id="username" required /><br />
<label for="password">Password:</label><br />
<input type="password" id="password" required /><br />
<input type="submit" value="Authorize" /><span id="isValid" class="checkContainer"> </span>
</form><hr />
<label for="serviceType" class="fieldDisabled">Method: </label>
<select id="serviceType" disabled>
<option></option>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>
The script is saved separately as authorize.js and invoked in the module as follows:
<script src="js/authorize.js"></script>
<script>
$(document).ready(function() {
Authorize.init();
});
</script>
Here's the module itself:
var s;
var Authorize = {
token: null,
settings: {
username: $("#username"),
password: $("#password"),
form: $("#authorize"),
validationIcon: $("#isValid"),
selector: $("#serviceType"),
selectorLabel: $("label[for='serviceType']"),
serviceSelector: $(".methodFieldDisabled"),
url: "redacted"
},
init: function() {
s = Authorize.settings;
this.bindUIActions();
},
bindUIActions: function() {
s.form.submit(function(event) {
event.preventDefault();
data = Authorize.buildJSON(s.username.val(), s.password.val());
Authorize.getToken(json);
});
},
buildJSON: function(username, password) {
var data = {};
data['grant_type'] = password;
data['username'] = username;
data['password'] = password;
return data;
},
getToken: function(data) {
$.ajax({
type: "POST",
url: s.url,
data: data,
success: function(json) {
Authorize.success(json);
},
error: function(json) {
Authorize.error(json);
}
});
},
success: function(json) {
Authorize.token = json.accessToken;
Authorize.revealServiceSelector();
},
error: function(json) {
Authorize.hideServiceSelector();
},
revealServiceSelector: function() {
s.serviceSelector.hide();
if(s.validationIcon.hasClass("invalid")) {
s.validationIcon.removeClass("invalid");
}
selectorLabel.removeClass("fieldDisabled");
selector.prop("disabled", false);
s.validationIcon.addClass("valid");
},
hideServiceSelector: function() {
s.serviceSelector.hide();
if(s.validationIcon.hasClass("valid")) {
s.validationIcon.removeClass("valid");
}
selectorLabel.addClass("fieldDisabled");
selector.prop("disabled", "disabled");
s.validationIcon.addClass("invalid");
}
};
I've been toiling over this for about a day now and can't seem to locate the point of failure. When the form is submitted, it redirects to the root directory of the server instead of executing the script as intended.
Just a few typos which stopped the code in its tracks. The submission was the default behavior as your code failed to complete.
Use a debugger to see the errors at runtime (get to know and love your F12 debugging tools in Chrome etc!):
1) You have the wrong variable (json instead of data) on the line below so you get an error:
bindUIActions: function () {
s.form.submit(function (event) {
event.preventDefault();
data = Authorize.buildJSON(s.username.val(), s.password.val());
Authorize.getToken(data); // <<<<<<<<<<<<<<<<<<<<<<<
});
2) You also failed to put your scope (s) on a couple of variables:
revealServiceSelector: function () {
s.serviceSelector.hide();
if (s.validationIcon.hasClass("invalid")) {
s.validationIcon.removeClass("invalid");
}
s.selectorLabel.removeClass("fieldDisabled");
s.selector.prop("disabled", false);
s.validationIcon.addClass("valid");
},
hideServiceSelector: function () {
s.serviceSelector.hide();
if (s.validationIcon.hasClass("valid")) {
s.validationIcon.removeClass("valid");
}
s.selectorLabel.addClass("fieldDisabled");
s.selector.prop("disabled", "disabled");
s.validationIcon.addClass("invalid");
}
Your from action is pointed to "\" which is the root of your directory. Instead point it to the file that contains the code you want to fire.
I have an ajax function on the initialize of the main router that seems to hinder the event of my signin button in signin.js. When I click the signin button, it doesn't perform its function, instead the browser places the inputs on the URL, (i.e. username and password).
But when I remove the ajax function on the initialize, I can successfully log in.
I've included some of the codes I'm working on. Thanks
main.js
initialize: function(){
$.ajax({
type: "GET",
url: "something here",
contentType: "application/json",
headers: {
'someVar': something here
},
statusCode: {
404: function() {
console.log('404: logged out');
if (!this.loginView) {
this.loginView = new LoginView();
}
$('.pagewrap').html(this.loginView.el);
},
200: function() {
console.log('200');
if (!this.homeView) {
this.homeView = new HomeView();
}
$('.pagewrap').html(this.homeView.el);
}
}
});
// return false;
},
signin.js
var SigninView = Backbone.View.extend ({
el: '#signin-container',
events: {
"click #btn-signin" : "submit"
},
submit: function () {
console.log('signin');
$.ajax({ ... });
return false;
}
});
var toSignin = new SigninView();
window.anotherSigninView = Backbone.View.extend({
initialize: function() {},
render: function() {}
});
home.js
window.HomeView = Backbone.View.extend ({
initialize: function() {
this.render();
},
render: function() {
$(this.el).html( this.template() );
return this;
}
});
some html
<form id="signin-container">
<table id="tbl-signin">
<tr>
<td><div class="input-box"><input class="input-text" type="text" name="username" placeholder="Username"></div></td>
<td><div class="input-box"><input class="input-text" type="password" name="password" placeholder="Password"></div></td>
<td><input id="btn-signin" class="button" value="Sign In"></td>
</tr>
<tr>
<td class="opt"><input class="checkbox" type="checkbox" name="rememberMe" value="true"><label class="opt-signin">Remember Me?</label></td>
<td class="opt"><a class="opt-signin" href="#">Forgot Password?</a></td>
<td></td>
</tr>
</table>
</form>
You need to prevent the default behaviour of the submit button in your click handler. You can do this like so:
var SigninView = Backbone.View.extend ({
el: '#signin-container',
events: {
"click #btn-signin" : "submit"
},
submit: function (event) {
event.preventDefault();
console.log('signin');
$.ajax({ ... });
}
});
Alternatively, you might consider using the html button element which won't attempt to submit the form it's associated with.
Ok, I figured out what's your problem :)
Here is an example that resumes your code jsfiddle.net/26xf4/6. The problem is that you don't call new SigninView(); (instantiate the view) hence its events are never bound.
So, in this example try to uncomment the ligne 43 and your code will work as expected, because when you instantiate a View (new SigninView()) its constructor calls the delegateEvents() function (you don't see this in your code, it's in the backbone.js) enabling the events you declare in your view :
events: {
"click #btn-signin" : "submit"
},
I don't know about your HTML mockup, my best guess is that you are catching the incorrect event here. If you are submitting a form, you should catch submit form event not click #some-button. Because even if you catch click event of button inside a form and return false, the form will be still submitted because those are 2 different events