I am trying to use bootstrap spinner to load upon button click while flask is processing the request but it's not working.
When I click the button, the request is sent to flask and it never gets to the javascript part for some reason.
To confirm that, I tried the same HTML code below on a separate HTML page and it worked.
So my question is: how to make the javascript code work in conjunction with the request being sent to flask as well.
the HTML and Javascript part goes this way:
<div class="container-fluid mt-3">
<p class="font-weight-bold">Deactivate User</p>
<br>
<form action="{{ url_for('deactivate_user')}}" method='POST'>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">#</span>
</div>
<input type="text" class="form-control" placeholder="Username" id="username" name="username" required>
</div>
<button type="submit" id="submit" class="btn btn-info btn-primary">Submit</button>
</form>
</div>
<script>
$('#submit').click(function () {
this.form.submit();
this.disabled = true;
this.html = '<button class="btn btn-primary" type="button" disabled> <span class="spinner-grow spinner-grow-sm" role="status" aria-hidden="true"></span><span class="sr-only">Loading...</span></button>'
});
</script>
Am I doing something wrong? I am pretty new to HTML so excuse my ignorance in advance.
You can use ajax
<div class="container-fluid mt-3">
<p class="font-weight-bold">Deactivate User</p>
<br />
<div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">#</span>
</div>
<input
type="text"
class="form-control"
placeholder="Username"
id="username"
name="username"
required
/>
</div>
<button id="submit" class="btn btn-info btn-primary">
Submit
</button>
</div>
</div>
Then
<script>
$('#submit').click(function (d) {
let username = $('#username').val();
$.post(
"url_for_deactivate_user",
{
username: username,
},
function (data, status) {
// if (data) { // validate response data here
this.disabled = true;
this.html = `<button class="btn btn-primary" type="button" disabled> <span class="spinner-grow spinner-grow-sm" role="status" aria-hidden="true"></span><span class="sr-only">Loading...</span></button>
`;
// }
}
);
});
</script>
NOTE: Make sure you replace url_for_deactivate_user properly and also that your server gives a response.
Related
I wrote a function that I can reuse in different pages for searching Images.
and I don't want page to be refresh when hitting enter.
without form it is working fine on onclick event.
How can I prevent page from reloading ?
Here is the form below, Thank you.
<form method="post" action="#">
<div class="input-group form-sm form-2 pl-0 m-b-20">
<input class="form-control " id="image_keyword" type="text" >
<div class="input-group-append">
<button type="submit" class="input-group-text" onsubmit="searchImages()">search</button>
</div>
</div>
</form>
JQuery function.
function searchImages()
{
let keyword = jQuery("#image_keyword").val();
let response = searchMedia('image',keyword);
console.log(response);
if(response.status === 'success')
{
// some code...
}
}
You need prevent the default behavior of onsubmit event.
function searchImages(e)
{
e.preventDefault();
let keyword = jQuery("#image_keyword").val();
let response = searchMedia('image',keyword);
console.log(response);
if(response.status === 'success')
{
let data = response.data;
console.log(data);
}
}
You need to use e.preventDefault() and addEventListener
function searchImages(e)
{
e = e || window.event
e.preventDefault();
let keyword = jQuery("#image_keyword").val();
let response = searchMedia('image',keyword);
console.log(response);
if(response.status === 'success')
{
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" action="#" onsubmit="searchImages(event)">
<div class="input-group form-sm form-2 pl-0 m-b-20">
<input class="form-control " id="image_keyword" type="text" >
<div class="input-group-append">
<button type="submit" class="input-group-text" >search</button>
</div>
</div>
</form>
Use onsubmit function in form tag instead of submit button.And pass event param.The prevent using e.preventDefault()
function searchImages(e) {
e.preventDefault();
console.log('ok')
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" action="#" onsubmit="searchImages(event)">
<div class="input-group form-sm form-2 pl-0 m-b-20">
<input class="form-control " id="image_keyword" type="text">
<div class="input-group-append">
<button type="submit" class="input-group-text" >search</button>
</div>
</div>
</form>
For Simple Jquery Approach .Define submit with in dom
$('#form_one').on('submit',function(e){
e.preventDefault();
console.log('ok')
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" action="#" id="form_one">
<div class="input-group form-sm form-2 pl-0 m-b-20">
<input class="form-control " id="image_keyword" type="text">
<div class="input-group-append">
<button type="submit" class="input-group-text" >search</button>
</div>
</div>
</form>
If you want to restrict the reload of page :
use :
event.preventDefault();
Change this line:
<button type="submit" class="input-group-text" onsubmit="searchImages()">search</button>
to
<button type="button" class="input-group-text" onclick="searchImages()">search</button>
No need to do anything else.
Is it possible to submit a form that have a submit button (by pressing enter)
I have two text fields by clicking the login button I am able to process the outcome but I am unable to do it by hitting enter.
Here is the HTML code(updated with full code)
this is signin.component.html
<div class="modal-content" style="padding: 10px;" id="login" *ngIf="show">
<div class="modal-body text-left">
<div class="login">
<h2>Login</h2>
<hr>
<div class="row socialButtons">
<div class="col-xs-12 col-sm-12 col-md-4">
<a class="btn btn-lg btn-block btn-facebook" (click)="signInFacebook()">
<i class="fa fa-facebook visible-xs"></i>
<span class="hidden-xs">Facebook</span>
</a>
</div>
<div class="col-xs-12 col-sm-12 col-md-4">
<a class="btn btn-lg btn-block btn-linked-in" (click)="signInLinkedin()">
<i class="fa fa-linkedin visible-xs"></i>
<span class="hidden-xs">Linkedin</span>
</a>
</div>
<div class="col-xs-12 col-sm-12 col-md-4">
<a class="btn btn-lg btn-block btn-google-plus" (click)="signInGoogle()">
<i class="fa fa-google-plus visible-xs"></i>
<span class="hidden-xs">Google</span>
</a>
</div>
</div>
<br>
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<form class="loginForm" #loginForm="ngForm" action="" autocomplete="off" method="POST">
<div class="form-group">
<label class="control-label" for="signupName">Email</label>
<input type="email" class="form-control" name="username" placeholder="Email" [(ngModel)]="username" required>
</div>
<div class="form-group">
<label class="control-label" for="signinPassword">Password</label>
<input type="password" class="form-control" name="password" placeholder="Password" [(ngModel)]="password" required>
</div>
</form>
<div class = "error"> {{ errMsg }} </div>
<button class="btn btn-lg btn-info btn-block btnlog" type="button" [disabled]="loginForm.invalid" (click)="login()">Login</button>
<hr>
</div>
</div>
<div class="row row-sm-offset-3">
<div class="col-xs-12 col-sm-12 col-md-6">
<p class="forgotPwd">
Forgot password? Reset
</p>
<p class="forgotPwd">
New User? Register now
</p>
</div>
</div>
</div>
</div>
</div>
<div *ngIf="showSignUp">
<app-sign-up></app-sign-up>
</div>
<div *ngIf="showForgotPassword">
<app-forgot-password></app-forgot-password>
</div>
this signin.component.ts file
import { Component, OnInit } from '#angular/core';
import {NgbModal, NgbActiveModal} from '#ng-bootstrap/ng-bootstrap';
import { Router } from '#angular/router';
import { AuthService } from '../services/auth/auth.service';
#Component({
selector: 'app-sign-in',
templateUrl: './sign-in.component.html',
styleUrls: ['./sign-in.component.css']
})
export class SignInComponent implements OnInit {
username:string;
password:string;
show = true;
showSignUp = false;
showForgotPassword = false;
errMsg = "";
constructor(
private authService: AuthService,
public activeModal: NgbActiveModal,
) { }
ngOnInit() {
this.authService.getEmitter().subscribe(res => {
if(res){
this.activeModal.dismiss('success');
}
else{
this.username = "";
this.password = "";
this.errMsg = "Invalid Username/Password";
}
})
}
signInGoogle(){
this.authService.loginWithGoogle();
}
signInFacebook(){
this.authService.loginWithFacebook();
}
signInLinkedin(){
this.authService.loginWithLinkedin();
}
logOut(){
this.authService.logOut();
}
login(){
this.authService.login(this.username,this.password);
}
reset(){
this.show = false;
this.showSignUp = false;
this.showForgotPassword = true;
}
signup(){
this.show = false;
this.showSignUp = true;
this.showForgotPassword = false;
}
}
Use (keyup.enter)="focusableSubmit.click()" to input Password and call #focusableSubmit to Button login, this would perform the task and same for button as shown in code below.
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<form class="loginForm" #loginForm="ngForm" action="" autocomplete="off" method="POST">
<div class="form-group">
<label class="control-label" for="signupName">Email</label>
<input type="email" class="form-control" name="username" placeholder="Email" [(ngModel)]="username" required>
</div>
<div class="form-group">
<label class="control-label" for="signinPassword">Password</label>
<input type="password" class="form-control" name="password" placeholder="Password" [(ngModel)]="password" required (keyup.enter)="focusableSubmit.click()">
</div>
</form>
<div class = "error"> {{ errMsg }} </div>
<button #focusableSubmit class="btn btn-lg btn-info btn-block btnlog" type="button" [disabled]="loginForm.invalid" (click)="login()">Login</button>
<hr>
</div>
</div>
Your button should be inside the form but you have closed it inside the two input fields.
Update your code like this
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<form class="loginForm" #loginForm="ngForm" action="" (submit)="login()" autocomplete="off" method="POST">
<div class="form-group">
<label class="control-label" for="signupName">Email</label>
<input type="email" class="form-control" name="username" placeholder="Email" [(ngModel)]="username" required>
</div>
<div class="form-group">
<label class="control-label" for="signinPassword">Password</label>
<input type="password" class="form-control" name="password" placeholder="Password" [(ngModel)]="password" required>
</div>
<div class = "error"> {{ errMsg }} </div>
<button type="submit" class="btn btn-lg btn-info btn-block btnlog" [disabled]="loginForm.invalid" (click)="login()">Login</button>
</form>
<hr>
</div>
</div>
Yes you can.
Usually, you need to put your code in action="". But this isn't old HTML, this is Angular, and it works with Javascript.
So, in order to do that, you need to add the novalidate tag, and tell the form what to do when you validate it.
You also need to declare a submit input instead of your button.
This would look like
<form class="loginForm" novalidate (ngSubmit)="login()" autocomplete="off">
<input type="submit" value="Login" class="btn btn-lg btn-info btn-block btnlog" [disabled]="loginForm.invalid" (click)="login()"/>
Yes it is possible and quite easy!
First you have to replace
(button)="button()"
with
(ngSubmit)="login()"
and remove the click handler from the button and change the type to submit.
Both lines changed look like this:
<form class="loginForm" #loginForm="ngForm" action="" autocomplete="off" (ngSubmit)="login()" method="POST">
and:
<button type="submit" class="btn btn-lg btn-info btn-block btnlog" [disabled]="loginForm.invalid">Login</button
Dont forget that this way, that button() does not get called.
Angular documentation is really helpful on most of the generel topics, maybe you should take a look there.
Additionally you should consider reading up on some basic information about forms. I personally suggest: forms on MDN and buttons on MDN.
Here's a strapped version of my form for sending comments.
As you see, I prevented the ENTER event on textarea and that will cause pressing ENTER while focused on textarea to not make a new line (but you can use SHIFT + ENTER).
Pressing enter sends a form.
<form #addCommentForm="ngForm" (keydown.enter)="addComment(addCommentForm.value)">
<textarea (keydown.enter)="$event.preventDefault()" type="text" placeholder="Leave a comment..." name="description" #description="ngModel" [(ngModel)]="comment.description"></textarea>
</form>
Give a try to
<button type="submit" class="btn btn-lg btn-info btn-block btnlog" [disabled]="loginForm.invalid" (click)="login()">Login</button>
CaseI create a new registration form and save it into database.The save process was succeed but I want to add some user interaction like when the data is successfully saved, the system notify user by toastr.I have create the code but it is not working.Please help.Below is the code.
Javascript and HTML
//toast a message upon successful registration
$(document).on('click', '.submit_button', function(e) {
console.log("submit button clicked");
e.preventDefault();
$.ajax({
type: "POST",
url: $("#regtenantform").attr('action'),
data: $("#regtenantform").serialize(),
success: function(response) {
if (response === "Success") {
$.toast({
heading: 'Welcome to my Elite admin',
text: 'Use the predefined ones, or specify a custom position object.',
position: 'top-right',
loaderBg:'#ff6849',
icon: 'success',
hideAfter: 3500,
stack: 6
});
window.reload;
} else {
alert("invalid username/password. Please try again");
}
}
});
});
<form id="regtenantform" name="regtenantform" class="form-material form-horizontal" method="post" action="../controllers/tenantcontroller.php" onsubmit="return ray.ajax()">
<div class="form-group">
<label class="col-md-12">Fullname <span class="help"> e.g. "Azizul"</span></label>
<div class="col-md-12">
<input type="text" class="form-control form-control-line" placeholder="Fullname" id="name" name="name" required="">
</div>
</div>
<div class="form-group">
<label class="col-md-12" for="example-email">Identification Number <span class="help"> e.g. "860102075555" (without "-" or space)</span></label>
<div class="col-md-12">
<input type="text" class="form-control form-control-line" placeholder="Id Number" id="ic" name="ic" required="">
</div>
</div>
<div class="form-group">
<label class="col-md-12">Phone Number <span class="help"> e.g. "0123456789"</span></label>
<div class="col-md-12">
<input type="text" class="form-control form-control-line" placeholder="No." id="contact" name="contact" required="">
</div>
</div>
<div class="form-group m-b-0">
<div class="col-sm-offset-3 col-sm-9 text-right">
<button type="button" class="btn btn-inverse waves-effect waves-light m-r-10" id="reset" name="reset">Reset</button>
<button type="submit" class="btn btn-info waves-effect waves-light" id="submit_button" name="submit_button">Save</button>
</div>
</div>
</form>
Here:
$(document).on('click', '.submit_button', function(e) {
^---CSS class
<button type="submit" class="btn btn-info waves-effect waves-light" id="submit_button" name="submit_button">Save</button>
^^----nowhere do you have a "submit_button" class
You have an ID of submit_button, so your click handler should be looking for #submit_button, not .submit_button
I'm trying to set up a login form who redirects the user to another page after submitting the form. However neither window.location.replace(), window.location.href, or window.open() seem to work and I can't figure out why. I checked on the developer tools and it gives me no error.
Here's the javascript:
function loginUtente(){
var email = document.getElementById('loginemail').value;
var password = document.getElementById('loginpassword').value;
var utente = localStorage.getItem(email);
if( utente != null && JSON.parse(utente).password == password){
window.alert("login effettuato!");
window.location.replace("http:/www.google.it");
}
else{
window.alert("Utente o password non corretti");
}
return false;
}
And here's the HTML:
<form class="form-group" id="formlogin" onsubmit="loginUtente()">
<label>Email</label>
<div class="input-group">
<div class="input-group-addon"><span class="glyphicon glyphicon-user"></span></div>
<input id="loginemail" type="text" name="nome" class="form-control" placeholder="Indirizzo Email" required ></input>
</div>
<br>
<label>Password</label>
<div class="input-group">
<div class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></div>
<input id="loginpassword" type="password" name="password" class="form-control" placeholder="Password" required>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success" ><span class="glyphicon glyphicon-send" ></span> Login</button>
</form>
Putting the return false inside the if is not working either.
The Google url is of course a placeholder url.
In the form tag you missed to add return statement :
<form class="form-group" id="formlogin" onsubmit="return loginUtente()">
So, form is submitted without waiting for response of function. and function code is not executed.
I have problem with inputs validation and ajax post. I use http://1000hz.github.io/bootstrap-validator/
here is my code of form:
<form id="order-form" class="form" action="" method="post" novalidate="true" role="form" data-toggle="validator">
<fieldset>
<div id="callback-type" class="btn-group">
<button class="btn btn-default private-callback btn-primary" type="button" data-type="private">
Private
</button>
<button class="btn btn-default public-callback" type="button" data-type="public">
Public
</button>
<input class="callback-type" type="hidden" id="callback-type-data" name="callback[type]" value="private">
</div>
</fieldset>
<fieldset style="border: none">
<section class="callback-time-select form-group">
<label class="input"> <i class="icon-prepend fa fa-user"></i>
<input class="callback-datetime" placeholder="<?=date('Y/m/d H:i');?>" type="text" name="callback[time]" id="callback-time" required/>
<div class="time-clear">
<i class="fa fa-times-circle"></i>
</div>
</label>
<div class="help-block with-errors"></div>
</section>
<section class="second callback-agent-section form-group">
<select class="callback-agent" name="callback[user]" style="width:100%" class="select2" id="select-callback-agent" required>
<option></option>
<option value="1">Name</option>
</select>
<div class="help-block with-errors"></div>
</section>
</fieldset>
<div class="tab-actions">
<button type="submit" class="btn btn-primary btn-sm submit-button callback-btn-create">Set Callback</button>
<button type="submit" class="btn btn-primary btn-sm submit-button callback-btn-update" style="display: none;">Update Callback</button>
<button type="button" class="btn btn-default btn-sm submit-button callback-btn-remove" style="display: none;">Remove</button>
</div>
</form>
And here is my javascript code:
$(document).on('click', '#dealing-modal #callback-tab .tab-actions .callback-btn-create', function(){
$(this).closest('form').validator().submit(function(e){
e.preventDefault();
if (!$('.has-error').length) {
self.create();
}
});
});
And self.create method:
create: function()
{
Application.Debug("Calllback.create");
var self = this;
var form = $(":input", this.window).serialize();
form = form + '&call_id=' + this.call.id;
$.post(Application.url+'callbacks/create', form, function(data){
if(data.status === true) {
self.callback = data.callback;
$(".callback-btn-create",self.window).css('display','none');
$(".callback-btn-update",self.window).css('display','inline');
$(".callback-btn-remove",self.window).css('display','inline');
} else {
Application.Debug("Calllback.create - ERROR");
}
});
}
I need to validate form inputs and send ajax post on click button. It initiate form submit, and when send post after form is valid.
And my problem is:
When inputs are empty and i push the button create, form validate it and i see the error text. Its fine! But when i clicked button 1 or 2 times and ect., and after i complete all inputs, method self.create(); doing ajax post as much as times i clicked button.
Where is the problem?
You just need to disable or display none below button after click and before ajax call and vice versa after successful response.
<button type="button" class="btn btn-primary btn-sm submit-button callback- btn-create">Set Callback</button>
var $submitBtn; // Lets say this is the jQuery object that contains the form button element.
$submitBtn.attr('disabled', true);
$.post().always(function () {
$submitBtn.attr('disabled', false);
});
And, have some disabled styling for your button like:
input[type="submit"][disabled] {
opacity: .4;
pointer-events: none;
}
Another approach:
var $form; // Lets say this is the jQuery object that contains the form element.
if ($form.data('posting')) {
return false; // We are already posting data, don't do anything.
}
$form.data('posting', true);
$.post().always(function () {
$form.data('posting', false);
});