Bootstrap Modal fires action one time and if I click again it will fire up twice and so on.
<div id="loginModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Log In</h4>
</div>
<div class="modal-body">
<h3>Username</h3>
<input type="text" id="userLogin" placeholder="Username">
<h3>Password</h3>
<input type="password" id="pwdLogin" placeholder="Password">
<br>
<br>
<input type="checkbox" id="rememberMe">Remember Me
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="btnLogin">Log In</button>
</div>
</div>
</div>
</div>
Here's the span that fires the modal.
<span id="comment"><a id="testComment" data-toggle="modal" href="#loginModal" class="btn btn-default">Add comment</a></span>
After I click the span the modal shows. I click the #btnLogin and then the action fires up one time, two times and so on.
javascript that interacts with the modal(the action is within the span click):
$("#testComment").click(function (event) {
if ($("#msg").val() == "" || $("#nombre").val() == "") {
alert("To send a comment fill your mail and message!");
event.stopPropagation();
}
else {
$("#btnLogin").click(function () {
alert("this also");
$(this).off('shown.bs.modal');
if ($("#userLogin").val() != "" && $("#pwdLogin").val() != "") {
var dataToSend = {
"action": "LOGIN"
, "username": $("#userLogin").val()
, "password": $("#pwdLogin").val()
, "remember": $("#rememberMe").is(":checked")
}
$.ajax({
url: "data/applicationLayer.php"
, type: "POST"
, data: dataToSend
, dataTpe: "json"
, success: function (jsonData) {
var data = {
"comment": $("#msg").val()
, "username": $("#username").val()
}
$.ajax({
url: "data/addComment.php"
, type: "POST"
, data: data
, dataType: "text"
, success: function (dataResponse) {
var newHTMLContent = "";
newHTMLContent += "<tr><td>" + data.username + "</td>" + "<td>" + data.comment + "</td></tr>";
$("#commentTable").append(newHTMLContent);
alert("Comment was added!");
}
, error: function (errorMsg) {
alert("Error adding comment in ajax");
}
});
}
, error: function (errorMsg) {
alert("Login Error");
}
});
}
else {
alert('Missing username or password.');
}
});
}
});
Just put $("#btnLogin").click event outside. Here is the my code or go with below link may be it can help you.
JSFiddle
JAVSCRIPT
$("#testComment").click(function(event) {
if ($("#msg").val() == "" || $("#nombre").val() == "") {
alert("To send a comment fill your mail and message!");
event.stopPropagation();
}
});
$("#btnLogin").click(function() {
alert("this also");
$(this).off('shown.bs.modal');
if ($("#userLogin").val() != "" && $("#pwdLogin").val() != "") {
var dataToSend = {
"action": "LOGIN",
"username": $("#userLogin").val(),
"password": $("#pwdLogin").val(),
"remember": $("#rememberMe").is(":checked")
}
$.ajax({
url: "data/applicationLayer.php",
type: "POST",
data: dataToSend,
dataTpe: "json",
success: function(jsonData) {
var data = {
"comment": $("#msg").val(),
"username": $("#username").val()
}
$.ajax({
url: "data/addComment.php",
type: "POST",
data: data,
dataType: "text",
success: function(dataResponse) {
var newHTMLContent = "";
newHTMLContent += "<tr><td>" + data.username + "</td>" + "<td>" + data.comment + "</td></tr>";
$("#commentTable").append(newHTMLContent);
alert("Comment was added!");
},
error: function(errorMsg) {
alert("Error adding comment in ajax");
}
});
},
error: function(errorMsg) {
alert("Login Error");
}
});
} else {
alert('Missing username or password.');
}
});
Related
I want validation onclick. I want that before sending data, validate function run, if there is an empty field then it show amessage and data should not be send to php file. else if there is no empty fields then it should send data to php file.Form and functions are given below
<form role="form" id="schclass_form" name="schclass_form">
<div class="form-group">
<label>Enter Class Name</label>
<input class="form-control" type="text" name="class1" id="class1" placeholder="For Example: 'one'">
</div>
<div class="addmore">
<button type="button" class="btn btn-default" id="addmoreclass">Add More</button>
</div>
<button type="button" class="btn btn-default" onClick="schclass(this.id)">Submit</button>
<button type="reset" class="btn btn-default">Reset</button>
</form>
function validateForm1() {
$('#schclass_form input[type="text"]').each(function(){
var data=""+$(this).val();
if(data=="")
{
swal("Oops...", "Please fill the empty fields first", "error");
}
});
}
here is function which is sending data to php file.
function schclass(a) {
if ($("#" + a).is("[disabled=disabled]")) {
return false
} else {
$("#" + a).attr("disabled", "disabled");
swal("Wait", "Request Initiate, Please Wait....", "info");
var b = $("#schclass_form").serialize() + "&type=schClass;
$.ajax({
type: "POST",
url: "include/function.php",
data: b,
cache: false,
success: function(c) {
try {
c = JSON.parse(c)
} catch (d) {
console.log(d);
swal("Oops...", "Error: Wrong response", "error");
return;
}
if ($.trim(c.result) == "success") {
swal("Success", "Message: "+c.message, "success");
} else {
swal("Oops...", "Error: "+c.message, "error");
}
},
error: function(e, c, d) {
swal("Oops...", "Error: "+d, "error");
}
})
}
$("#" + a).removeAttr("disabled");
return false;
}
I suggest making the validateForm1() function return true/false if valid/invalid, then calling it from an if statement in your schclass(a) function, if it returns true then submit, else don't submit.
Here is your code with the suggested edits:
<form role="form" id="schclass_form" name="schclass_form">
<div class="form-group">
<label>Enter Class Name</label>
<input class="form-control" type="text" name="class1" id="class1" placeholder="For Example: 'one'">
</div>
<div class="addmore">
<button type="button" class="btn btn-default" id="addmoreclass">Add More</button>
</div>
<button type="button" class="btn btn-default" onClick="schclass(this.id)">Submit</button>
<button type="reset" class="btn btn-default">Reset</button>
</form>
function validateForm1() {
var valid = true;
$('#schclass_form input[type="text"]').each(function(){
var data=""+$(this).val();
if(data=="")
{
valid = false;
}
});
return valid;
}
function schclass(a) {
if ($("#" + a).is("[disabled=disabled]")) {
return false
} else {
if (validateForm1()) {
$("#" + a).attr("disabled", "disabled");
swal("Wait", "Request Initiate, Please Wait....", "info");
var b = $("#schclass_form").serialize() + "&type=schClass;
$.ajax({
type: "POST",
url: "include/function.php",
data: b,
cache: false,
success: function(c) {
try {
c = JSON.parse(c)
} catch (d) {
console.log(d);
swal("Oops...", "Error: Wrong response", "error");
return;
}
if ($.trim(c.result) == "success") {
swal("Success", "Message: "+c.message, "success");
} else {
swal("Oops...", "Error: "+c.message, "error");
}
},
error: function(e, c, d) {
swal("Oops...", "Error: "+d, "error");
}
})
} else {
swal("Oops...", "Please fill the empty fields first", "error");
}
}
$("#" + a).removeAttr("disabled");
return false;
}
i added on message Box and i am posting that data but not adding in my DB.
when i am trying to click Confirm button it is not saving in data-base how it will save to data-base can you please help me.
enter image description here
var leaveManagement= {
leaveData: null,
showModal: function(data) {
leaveManagement.leaveData = data;
$('#adminComment').val("");
$('#IsPaidLeave').prop('checked', false);
if ($(data).val() === "Reject") {
$(".form-check").hide();
} else {
var leaveTypeId = $(leaveManagement.leaveData).attr('data-leaveTypeId');
var userId = $(leaveManagement.leaveData).attr('data-employeeId');
if (leaveTypeId !== "" && leaveTypeId !== null && userId !== "" && userId !== null) {
$.ajax({
url: "/PayRoll/Leave/GetEmployeeLeaveTypeCount?employeeId=" +userId+"&leaveTypeId=" +leaveTypeId,
type: 'GET',
async: false,
contentType: 'application/json; charset=utf-8',
success: function (data) {
$('#leaveCount').html('<span class="badge badge-outline badge-primary">Remaining Leave : '+data+'</span>');
},
error: function (e) {
}
});
}
$(".form-check").show();
}
$('#showCommentModal').modal('show');
},
changeRequest: function () {
if (leaveManagement.leaveData !== null) {
debugger;
var leaveId;
if ($(leaveManagement.leaveData).val() === "Approve") {
leaveId = $(leaveManagement.leaveData).attr('data-id');
leaveManagement.processRequest(leaveId, true, false);
} else if ($(leaveManagement.leaveData).val() === "Reject") {
leaveId = $(leaveManagement.leaveData).attr('data-id');
leaveManagement.processRequest(leaveId, false, true);
}
}
},
processRequest: function(leaveId, isApproved, isRejected) {
var comment = $('#adminComment').val();
var isPaidLeave = $('#IsPaidLeave').prop('checked');
$.ajax({
url: "/PayRoll/Leave/RespondToLeaveRequest/?leaveId=" +
leaveId +
"&isApproved=" +
isApproved +
"&IsRejected=" +
isRejected +
"&comment=" +
comment +
"&isPaidLeave=" +
isPaidLeave,
type: "POST",
async: false,
contentType: "application/json; charset=utf-8",
success: function (data) {
if (!data.success) {
$.notify(data.ResponseText, { position: "top right", className: "success" });
} else {
$.notify('Updated', { position: "top right", className: "success" });
}
$("#OpenLeaveRequestGrid").data('kendoGrid').dataSource.read();
$("#ClosedLeaveRequestGrid").data('kendoGrid').dataSource.read();
$('#adminComment').val("");
$('#IsPaidLeave').prop('checked', false);
$('#IsPaid').prop('checked', false);
},
error: function(data) {
console.log(data);
$.notify('Error', { position: "top right", className: "error" });
}
});
},
this is the button where if i click this button its should be save my comment data.
div class="modal-footer">
<button type="button" class="btn btn-warning" onclick="leaveManagement.changeRequest(this);" data-dismiss="modal" value="Confirm" id="bntconfirm">Confirm</button>#*<span class="fa fa-check"> Confirm</span>*#
</div>
this is the box where am writing comment.
I'm working on a simple CRUD application where I have a sign in, sign up, and account section for the user. Once the user signs in, then clicks account, there is the option to edit and save your changes. You'll notice I have "here is where you want to change the disable to true" and "here is where you will update the user information in the database". This is where I am supposed to implement the code. How do I actually get those edit and save buttons to work through javascript? Here is my code:
HTML:
<nav>
<div>HOME</div>
<div>ABOUT</div>
<div>SPEAKERS</div>
<div>INFO</div>
<div class="join-button">
JOIN IN
<div class="join-holder">
<div class="sign-in">
<form>
<h2>Sign In</h2>
<label>User Name:</label>
<input id="username" type="text" value="name#name.com">
<label>Password:</label>
<input id="siPW" type="password" value="12345678">
<input class="submit-button si-submit" type="submit">
</form>
</div>
<div class="sign-up">
<form>
<h2>Sign Up</h2>
<label>Name:</label>
<input id="fullName" type="text" value="name">
<label>Email:</label>
<input id="email" type="email" value="name#name.com">
<label>Password:</label>
<input id="pw" type="password" value="12345678">
<input class="submit-button su-submit" type="submit">
</form>
</div>
</div>
</div>
<div class="account">Account</div>
<div class="signOut">Sign Out</div>
</nav>
<div class="home">
Home
</div>
JS:
function setBindings() {
$(".account").click(function (e) {
var ui = DATA.getUserInfo();
if($.isEmptyObject(ui)){
swal("Oops...", "You need to sign in!", "error");
}else{
$(".home").html('<label>Name:</label><input disabled="true" id="userFullName" value="' + ui.fullName +'" type="text"><button class="edit">Edit</button><button class="save">Save</button>');
$(".edit").click(function (e) {
//here is where you want to change the disable to true
});
$(".save").click(function (e) {
//here is where you will update the user information in the database
})
}
});
$(".signOut").click(function (e) {
DATA.signOut();
});
$(".su-submit").click(function (e) {
e.preventDefault();
var fullName = $("#fullName").val(),
email = $("#email").val(),
pw = $("#pw").val(),
cpw = $("#cPw").val();
if(fullName == ""){
swal("Oops...", "You need a name!", "error");
}else if(!validateEmail(email)){
swal("Oops...", "Your email is not valid!", "error");
}else if(pw == "" || pw.length < 8){
swal("Oops...", "Your password needs to be longer than 8!", "error");
}else if(cpw == "" || cpw.length < 8 || pw != cpw){
swal("Oops...", "Your passwords don't match!", "error");
}else{
var info = {
"fullName": fullName,
"email": email,
"password": pw
};
DATA.addUser(info, addedUser);
// swal("Congrats", "You are signed up!", "success");
}
});
$(".si-submit").click(function (e) {
e.preventDefault();
var username = $("#username").val(),
pw = $("#siPW").val();
if(username == "" || validateEmail(username) == false){
swal("Oops...", "You need a username!", "error");
}else if(pw == "" || pw.length < 8){
swal("Oops...", "Your password needs to be longer than 8!", "error");
}else{
DATA.checkUser(username, pw, userSignIn);
}
});
}
function addedUser(data) {
console.log("data " , data);
}
function userSignIn(data) {
console.log(data.fullName);
swal("Congrats", data .fullName + " You are signed in!", "success");
};
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
$(document).ready(function () {
setBindings();
});
Data JS:
var userLoggedIn = {};
var _checkUser = function (username, password, callback) {
$.ajax({
url: _baseQueryURL + 'q={"email":"' + username + '","password":"' + password +'"}' + _queryApiKey,
type: "GET",
contentType: "application/json"
}).done(function (data) {
userLoggedIn = data[0];
callback(data[0]);
}).fail(function (error) {
console.log("error " + error);
});
};
var _addUser = function (userInfo, callback) {
console.log(userInfo.email + ' ' + userInfo.password);
$.ajax({
url: _baseQueryURL + 'q={"email":"' + userInfo.email + '","password":"' + userInfo.password +'"}&c=true' + _queryApiKey,
type: "GET",
contentType: "application/json"
}).done(function (data) {
if(data == 0){
$.ajax({
url: _baseURL + _apiKey,
data: JSON.stringify( userInfo ),
type: "POST",
contentType: "application/json"
}).done(function (data) {
userLoggedIn = data;
callback(data);
}).fail(function (error) {
swal("Oops...", "You have an error!", "error");
});
}else if(data == 1){
swal("Oops...", "You are already signed up. Please Sign in!", "error");
}
}).fail(function (error) {
console.log("error " + error);
});
};
var _signOut = function () {
userLoggedIn = {};
};
var _getUserInfo = function () {
return userLoggedIn;
};
return {
checkUser: _checkUser,
addUser: _addUser,
signOut: _signOut,
getUserInfo: _getUserInfo
}
})();
I have the following problem, I have performed a function to update my data with PHP and Codeigniter, using AJAX too .. everything works fine, but it turns out that I want to validate my form using jquery-validate before performing the AJAX request, for that already I have my validation rules and my code is as follows:
function edit(id = null) {
if (!id) {
alert('error');
return;
}
$.ajax({
url: 'roles/get_data_id/' + id,
type: 'post',
dataType: 'json',
success: function(response) {
$("#edit_name").val(response.Name);
$("#edit_description").val(response.Description);
$("#form_edit").unbind('submit').bind('submit', function() {
var form = $(this);
$.ajax({
url: form.attr('action') + '/' + id,
type: 'post',
data: form.serialize(),
dataType: 'json',
success: function(response) {
if(response.success === true) {
$("#modal_edit").modal('hide');
alert('The data were updated');
$("#form_edit")[0].reset();
table_data.ajax.reload(null, false);
} else {
$("#modal_edit").modal('hide');
alert('Error updating data');
}
}// /succes
}); // /ajax
return false;
});
}
});
}
The code works fine .. update my data .. now my question is where to add the following code with my validation rules:
$('#form_edit').validate({
highlight: function (input) {
$(input).parents('.form-line').addClass('error');
},
unhighlight: function (input) {
$(input).parents('.form-line').removeClass('error');
},
errorPlacement: function (error, element) {
$(element).parents('.form-group').append(error);
}
});
This is my current code:
function edit(id = null) {
if (!id) {
alert('error');
return;
}
$.ajax({
url: 'roles/get_data_id/' + id,
type: 'post',
dataType: 'json',
success: function(response) {
$("#edit_name").val(response.Name);
$("#edit_description").val(response.Description);
$('#form_edit').validate({
highlight: function(input) {
$(input).parents('.form-line').addClass('error');
},
unhighlight: function(input) {
$(input).parents('.form-line').removeClass('error');
},
errorPlacement: function(error, element) {
$(element).parents('.form-group').append(error);
},
submitHandler: function() {
$.ajax({
url: form.attr('action') + '/' + id,
type: 'post',
data: form.serialize(),
dataType: 'json',
success: function(response) {
if (response.success === true) {
$("#modal_edit").modal('hide');
alert('The data were updated');
$("#form_edit")[0].reset();
table_data.ajax.reload(null, false);
} else {
$("#modal_edit").modal('hide');
alert('Error updating data');
}
} // /succes
}); // /ajax
return false;
}
});
}
});
}
this code my form:
<div class="modal fade" id="modal_edit" tabindex="-1" role="dialog">
<div class="modal-dialog modal-sm" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="smallModalLabel">Edit rol</h4>
</div>
<form id="form_edit" action="<?php echo base_url();?>rol/edit" method="POST">
<div class="modal-body">
<div class="form-group form-float">
<label class="form-label">Name</label>
<div class="form-line">
<input type="text" id="edit_name" name="edit_name" class="form-control" maxlength="20" minlength="5" required>
</div>
</div>
<div class="form-group form-float">
<label class="form-label">Description</label>
<div class="form-line">
<textarea id="edit_description" name="edit_description" rows="3" class="form-control no-resize" required></textarea>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-link waves-effect">update</button>
<button type="button" class="btn btn-link waves-effect" data-dismiss="modal">Cancel</button>
</div>
</form>
</div>
</div>
</div>
You can use the submitHandler provided by the jQuery validation, this way the AJAX will fire only when the validation rules are passed:
$('#form_edit').validate({
highlight: function(input) {
$(input).parents('.form-line').addClass('error');
},
unhighlight: function(input) {
$(input).parents('.form-line').removeClass('error');
},
errorPlacement: function(error, element) {
$(element).parents('.form-group').append(error);
},
submitHandler: function() {
//your AJAX code goes here
edit(your_id_param_goes_here);
}
});
I have made you a WORKING DEMO,
I hope you will figure out how to continue from there.
HTML Changes:
<form id="form_edit">
<button id="submitForm" type="submit" class="btn btn-link waves-effect">update</button>
JavaScript:
$(document).ready(function() {
$("#submitForm").on("click", edit);
// introduce the validation rules to the form!
$('#form_edit')
.validate({
highlight: function(input) {
$(input).parents('.form-line').addClass('error');
},
unhighlight: function(input) {
$(input).parents('.form-line').removeClass('error');
},
errorPlacement: function(error, element) {
$(element).parents('.form-group').append(error);
},
submitHandler: function(form) {
//Will execute only when the form passed validation.
OnSubmit(form);
}
});
function OnSubmit(form) {
$.ajax({
url: form.attr('action') + '/' + id,
type: 'post',
data: form.serialize(),
dataType: 'json',
success: function(response) {
if (response.success === true) {
$("#modal_edit").modal('hide');
alert('The data were updated');
$("#form_edit")[0].reset();
table_data.ajax.reload(null, false);
} else {
$("#modal_edit").modal('hide');
alert('Error updating data');
}
} // /success
}); // /ajax
}
function edit(id = null) {
if (!id) {
alert('error');
return;
}
$.ajax({
url: 'roles/get_data_id/' + id,
type: 'post',
dataType: 'json',
success: function(response) {
$("#edit_name").val(response.Name);
$("#edit_description").val(response.Description);
return false;
}
});
}
});
I'm trying to pass all my form fields, to a ajax function where i will insert the user into the database.
But for some reason, my alert (in my JS file) isn't showing anything.
Any ideas what i'm doing wrong?
My HTML:
<form id="signupForm">
<input id="signupFormEmail" type="text" name="email" placeholder=" E-mail"><br />
<input id="signupFormPassword" type="text" name="password" placeholder=" Password"><br />
<input id="signupFormUsername" type="text" name="userName" placeholder=" User Name"><br />
<input id="submitSignup" type="button" value="SIGN UP" onclick="signUp(this);">
</form>
My javascript file:
function signUp(elem)
{
var postData = $(this).serializeArray();
//$('#myResults').html(postData);
alert($.param($(elem).serializeArray()));
if($(elem).parent().children('#signupFormEmail').val() != ''){
// verifica se o email já existe
$.ajax(
{
url: "/newsletter/check-email/",
type: "POST",
data: {type:'check',email:$(elem).parent().children('#signupFormEmail').val()}
}).done(function(response)
{
if(response == -1) {
$.ajax(
{
url: "/newsignup/registare/",
type: "POST",
data: postData
}).done(function(userCreated) {
if(userCreated == 1) {
alert('user created');
/*
$(elem).parent().children('#signupForm').val('');
$('#signUpCompleted').show();
*/
}
else
{
/*$('#signUpError').show();*/
alert('user not created');
}
})
//testing
//$('#signUpCompleted').show();
}
else //testing
{
$('.emailError').show(); //testing
}
}
);
}
}
It looks like you are serializing the element itself. You have to serialize the form, please check this out.
function signUp(elem)
{
var postData = $('form').serialize();
//$('#myResults').html(postData);
alert(postData);
if($(elem).parent().children('#signupFormEmail').val() != ''){
// verifica se o email já existe
$.ajax(
{
url: "/newsletter/check-email/",
type: "POST",
data: {type:'check',email:$(elem).parent().children('#signupFormEmail').val()}
}).done(function(response)
{
if(response == -1) {
$.ajax(
{
url: "/newsignup/registare/",
type: "POST",
data: postData
}).done(function(userCreated) {
if(userCreated == 1) {
alert('user created');
/*
$(elem).parent().children('#signupForm').val('');
$('#signUpCompleted').show();
*/
}
else
{
/*$('#signUpError').show();*/
alert('user not created');
}
})
//testing
//$('#signUpCompleted').show();
}
else //testing
{
$('.emailError').show(); //testing
}
}
);
}
}
In your onclick attribute, this is not the FORM; this is the button you clicked.