I Have a change password form which I have tried to code so that it gets submitted through ajax.
I needed to do validation too.
Below is the code that I've written. Is there anyway so that we can use this js ajax function for multiple modal forms?
Or will we need to create a seperate function for submitting each modal form?
Also I wanted to make the parent page reload after user closes the modal so I have added this code:
$('#edit').on('hidden.bs.modal', function() {
location.reload();
});
but it reloads the page when someone clicks cancel button too. Is there any way to prevent reloading when clicking cancel button and only do reloading only by clicking "x".
Here is the code
index.php file where the modal is
<p data-placement="top" data-toggle="tooltip" title="Edit" data-original-title="Edit">
<button class="btn btn-primary btn-xs" data-title="Edit" data-toggle="modal" data-target="#edit" data-backdrop="static" data-keyboard="false">
<span class="glyphicon glyphicon-pencil"> Edit</span>
</button>
</p>
<div class="modal fade" id="edit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Edit Your Detail</h4>
</div>
<!--/.modal-header-->
<div class="modal-body">
<form method="post" id="updateForm" action="update-info.php">
<input type="hidden" name="userID" value="<?php echo $_SESSION['user']; ?>" />
<div class="form-group">
<label for="customer_name">Customer Name :</label>
<input class="form-control" type="text" name="customer_name" id="customer_name" value="<?php echo $userRow['fullName']; ?>" />
</div>
<h4><u><strong>Change Password</strong></u></h4>
<div class="form-group" id="currentPass-group">
<label for="current_pass">Current Password :</label>
<input class="form-control" type="password" name="current_pass" id="current_pass">
</div>
<div class="form-group">
<label for="new_pass">New Password :</label>
<input class="form-control" type="password" name="new_pass" id="new_pass">
</div>
<div class="form-group">
<label for="confirm_pass">Confirm Password :</label>
<input class="form-control" type="password" name="confirm_pass" id="confirm_pass">
</div>
<div class="modal-footer">
<!-- <input type="submit" name="submit" class="btn btn-block btn-warning" value="Save changes" /> -->
<button type="submit" name="submit" class="btn btn-success" id="submitForm" value="Save changes">Save Changes</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!--/.modal -->
custom.js file:
$('#edit').on('hidden.bs.modal', function() {
location.reload();
});
/* must apply only after HTML has loaded */
$(document).ready(function() {
$("#updateForm").on("submit", function(e) {
$(".error").hide();
var hasError = false;
var currentpass = $("#current_pass").val();
var newpass = $("#new_pass").val();
var cnfpass = $("#confirm_pass").val();
if (currentpass == '') {
$("#current_pass").after('<span class="error text-danger"><em>Please enter your current password.</em></span>');
//$('#currentPass-group').addClass('has-error'); // add the error class to show red input
//$('#current_pass').append('<div class="help-block">Please enter your current password.</div>'); // add the actual error message under our input
hasError = true;
} else if (newpass == '') {
$("#new_pass").after('<span class="error text-danger"><em>Please enter a password.</em></span>');
hasError = true;
} else if (cnfpass == '') {
$("#confirm_pass").after('<span class="error text-danger"><em>Please re-enter your password.</em></span>');
hasError = true;
} else if (newpass != cnfpass) {
$("#confirm_pass").after('<span class="error text-danger"><em>Passwords do not match.</em></span>');
hasError = true;
}
if (hasError == true) {
return false;
}
if (hasError == false) {
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url: formURL,
type: "POST",
data: postData,
success: function(data, textStatus, jqXHR) {
$('#edit .modal-header .modal-title').html("Result");
$('#edit .modal-body').html(data);
$("#submitForm").remove();
//document.location.reload();
},
error: function(jqXHR, status, error) {
console.log(status + ": " + error);
}
});
e.preventDefault();
}
});
$("#submitForm").on('click', function() {
$("#updateForm").submit();
});
});
update-info.php
To use this code for multiple form add ajax code in one function and call that function whenever you want to.
To prevent page from reloading when someone click on cancel
Instead of using
$('#edit').on('hidden.bs.modal', function () {
location.reload();
});
Add one click event on cross and then reload page by location.reload();
You can use e.preventDefault(); and instead of submit use click event
$("#submitForm").on("click", function(e) {
e.preventDefault();
Related
So idea is Id like the user to click a button, have the page submit through the post method which will populate fields for a form, then return the page with a modal displayed. I have this working, except the issue is that the page is at the top even if the user clicked halfway down. Id like the page to redisplay where it was, with the modal displaying.
I know that there is a fragment parameter, but only for redirecttopage and not page()? Sending it back to get resets everything, so thats not realy ideal. Ive also tried altering the url with javascript which works with setting the page position, but somehow it will not display the modal with that?
Does anyone know how to easily return the page in the post method to a specific spot on the page?
Javascript: (Modal shows up for one second then disappers when it goes to the page position)
function OnLoad() { //Used for redisplaying on error purposes
if ("#TempData["EditingParty"]" == "Yes") {
var loadedURL = window.location.href;
var fragmentPieceOfURL = "#TempData["EndOfURL"]"
location.href = loadedURL + fragmentPieceOfURL;
document.getElementById("EditUsersForm").style.display = "inline-block";
}
else {
document.getElementById("EditUsersForm").style.display = "none";
}
}
Cshtml
Button that goes to post (i is counter to keep track of anchor tag for redisplay location):
<a id="#i"></a>
<button type="submit" style="white-space:nowrap" class="btn btn-secondary btn-sm" formnovalidate asp-page-handler="DisplayEdit" asp-route-id="#Model.UsersOnCaseList.ElementAtOrDefault(i).UserID" asp-route-AttorneyRole="#Model.UsersOnCaseList.ElementAtOrDefault(i).AttorneyRole" asp-route-email="#Model.UsersOnCaseList.ElementAtOrDefault(i).EmailAddress" asp-route-pAttorneyRoleID="#Model.UsersOnCaseList.ElementAtOrDefault(i).AttorneyRoleID" asp-route-PageFragment="#i" asp-route-pEditAttorneyUserID="#Model.UsersOnCaseList.ElementAtOrDefault(i).UserID">Edit <i class="fas fa-ribbon"></i></button>
Modal:
<div class="modal" tabindex="-1" role="dialog" id="EditUsersForm" style="display:none">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Edit User</h5>
<button type="button" onclick="closeEditUsersForm()" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="form-group" style="margin-top:15px;padding-left:15px">
<label asp-for="EditUserEmailInput"></label> <span class="red">*</span>
<input asp-for="EditUserEmailInput" class="form-control" id="EmailInputBox" value="#Model.EditUserEmailInput" style="display:block;width:25em" />
<span style="display:block" asp-validation-for="EditUserEmailInput" class="text-danger" id="AddUserInputValidation"></span>
</div>
<div class="form-group" style="margin-top:15px;padding-left:15px">
<label class="control-label">Role</label> <span class="red">*</span>
<select asp-for="AttorneyRoleIDEditForm" asp-items="#(new SelectList(Model.AttorneyRolesList, "AttorneyRoleID","AttorneyRole"))" name="AttorneyRoleIDEditForm" id="SelectAttorneyRoleIDEditForm" class="form-control" style="width:25em" onchange="DidSelectPlaintiffEdit()">
<option class="form-control" value=-1>Select a Role</option>
</select>
<span asp-validation-for="AttorneyRoleIDEditForm" class="text-danger"></span>
</div>
<div class="form-group" style="margin-top:15px;padding-left:15px">
<label asp-for="EditUserPartyInput"></label> <span class="red">*</span><br />
<input asp-for="EditUserPartyInput" value="#Model.EditUserPartyInput" class="form-control" id="PartyNameInputEdit" style="display:inline-block;width:25em" />
<span style="display:block" asp-validation-for="EditUserPartyInput" class="text-danger" id="PartyNameInputValidation"></span>
</div>
<div class="modal-footer">
<button class="btn btn-primary" style="margin:0 auto" asp-page-handler="SaveUserEdits" asp-route-UserBeingEdited="" id="EditSubmitButton" name="EditUserSubmit" value="Yes">Submit</button>
<button class="btn btn-primary" style="margin:0 auto; display:none" asp-page-handler="SaveUserEdits" disabled id="SubmitButtonDisabled" name="AddUserSubmit" value="Yes">Submit</button>
</div>
</div>
</div>
</div>
CS file:
public IActionResult OnPostDisplayEdit(int id, string email,string AttorneyRole,int pAttorneyRoleID,int pAttorney,int pEditAttorneyUserID,int PageFragment)
{
EditUserEmailInput = email;
string curDictionaryAttorneyRole;
if (AttorneyRole.Contains('('))//Just because in development user didnt always have ability to enter a party
{
curDictionaryAttorneyRole = AttorneyRole.Split(new[] { '(' }, 2)[0].Trim();
EditUserPartyInput = AttorneyRole.Split(new[] { '(' }, 2)[1];
var LastRightParenIndex = EditUserPartyInput.LastIndexOf(')');
EditUserPartyInput = EditUserPartyInput.Substring(0, LastRightParenIndex); //Pulling the right parenthesis out
}
else //Its just the dictionary role
{
curDictionaryAttorneyRole = AttorneyRole;
EditUserPartyInput = null;
}
TempData["EditingParty"] = "Yes";
TempData["EndOfURL"] = PageFragment.ToString() + "&#" + PageFragment.ToString();
SetFileSequenceField();
ModelState.Clear(); //Used to remove the validations
SetAttorneyRoleList();
var selectedIndex = AttorneyRolesList.Where(arl => arl.AttorneyRole == curDictionaryAttorneyRole).Select(arl => arl.AttorneyRoleID).FirstOrDefault();
AttorneyRoleIDEditForm = selectedIndex;
EditAttorneyUserID = pEditAttorneyUserID;
UneditedEmail = email;
UneditedAttorneyRoleID = pAttorneyRoleID;
PopulateUserList();
//return RedirectToPage("AddUsersToCase","GET",fragment:PageFragment.ToString());
return Page();
//var PageURL = Page();
//PageURL = PageURL. + "&#" + PageFragment.ToString();
//return PageURL;
}
You can try to replace
location.href = loadedURL + fragmentPieceOfURL;
to
history.pushState({}, null, loadedURL + fragmentPieceOfURL);
So that the page will not be refreshed with location.href.
I create one form which includes select2 control.and i have data in database.
Now I want to fetch value of particular data value into select2 control when edit the form. My selected select value is store in one variable Now i want that value dispaly in select2 control inside the edit form and i dont know how ..
here is my edit form code:
<div id="editm" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog modal-sm" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Update Rayon</h4>
</div>
<div class="modal-body">
<form id="validate1" method="POST">
<div class="form-group">
<label class="control-label">Kode Rayon</label>
<div>
<input type="text" class="form-control" id="edit_Kode_rayon" name="edit_Kode_rayon" placeholder="Kode Rayon" readonly>
</div>
</div>
<div class="form-group">
<label class="control-label">Nama Rayon</label>
<div>
<input type="text" class="form-control" id="edit_nama_rayon" name="edit_nama_rayon" placeholder="Nama Center" >
</div>
</div>
<div class="form-group">
<label class="control-label">Nama Region</label>
<div>
<!-- HERE IS THE SELECT2 THAT IM TALKING ABOUT.. -->
<select class="form-control kode_region" id="nRegionE" name="kode_region" style="width: 100%;">
<option value=""></option>
</select>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="update" class="btn btn-primary">Update</button>
</div>
</div>
</div>
here is jquery code for edit button:
$(document).on("click", "#edit", function(e){
e.preventDefault();
var editid = $(this).attr("value");
$.ajax({
url: "<?php echo base_url();?>Rayon/editdata",
type: "POST",
dataType: "json",
data:{editid: editid},
success: function(data){
if(data.responce == "success"){
$('#editm').modal('show');
$("#edit_Kode_rayon").val(data.posts.kode_rayon);
$("#edit_nama_rayon").val(data.posts.nama_rayon);
//$("#nRegionE").val(data.posts.kode_region);<-- I TRIED LIKE THIS .. NOT WORK -->
//$("#nRegionE").select2().select2('val',data.posts.kode_region);<-- I TRIED LIKE THIS . NOT WORK-->
$('#nRegionE').val(data.posts.kode_region).trigger("change");<-- EVEN THIS ONE IS NOT WORK -->
}else{
toastr["error"](data.message);}
}
});
});
and here is my Select2 script that im using it for inssert and my edit form:
$(function () {$('.kode_region').select2({
//placeholder: "Please select region",allowClear: true,
ajax: {
dataType: 'json',
url: '<?=site_url('Bonus/nregion')?>',
type: "post",
delay: 250,
data: function(params) {
return {search: params.term}},
processResults: function (data, page) {
return {results: data};
},
}
})});
just to make it clear i took a screenshot of my edit form:
all what i want is to fetch the value of data into select2 form control of Edit Form .. can anyone help me to do that ? n i'll be so thankful.
You are fetching options list correctly in data.posts.kode_region,
then update this line
$("#nRegionE").val(data.posts.kode_region);
to this
$("#nRegionE").html('<option value = "'+data.posts.kode_region+'" selected >'+data.posts.kode_region+'</option>');
and don't forget to comment this line
$('#nRegionE').val(data.posts.kode_region).trigger("change");
I am dam sure this will work for you
$("select#nRegionE option").val("hello"); //Change hello string to your record Id
$("select#nRegionE option").html(data.posts.kode_region);
I am coding a website from 0 to 100 Now I'm coding the Login section.
This Is My HTML Code :
<div class="limiter">
<div class="container-login100">
<div class="wrap-login100 p-l-55 p-r-55 p-t-65 p-b-54">
<form class="login100-form validate-form">
<span class="login100-form-title p-b-49">
ورود
</span>
<div class="wrap-input100 validate-input m-b-23 text-right">
<span class="label-input100">ایمیل / شماره موبایل</span>
<input class="input100" type="email" id="UserEmailLogin" placeholder="ایمیل / شماره موبایل">
<span class="focus-input100" data-symbol=""></span>
</div>
<div class="wrap-input100 validate-input text-right">
<span class="label-input100">رمز عبور</span>
<input class="input100" type="password" id="UserPasswordLogin" placeholder="رمز عبور خود را وارد کنید">
<span class="focus-input100" data-symbol=""></span>
</div>
<div class="modal fade" id="MessageModalLogin" tabindex="-1" role="dialog" aria-labelledby="MessageModalLoginLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="MessageModalLoginLabel">پیغام سیستمی</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body text-right">
<p id="ModalMessageBodyLogin"></p>
<p id="EmailSendMessageLogin"></p>
</div>
<div class="modal-footer" id="ModalFooterActiveLogin">
</div>
</div>
</div>
</div>
<div class="text-right p-t-8 p-b-31">
<a href="#">
رمز عبور خود را فراموش کرده اید ؟
</a>
</div>
<div class="container-login100-form-btn">
<div class="wrap-login100-form-btn">
<div class="login100-form-bgbtn"></div>
<button class="login100-form-btn" type="button" onclick="Login()" data-toggle="modal" data-target="#MessageModalLogin">
ورود
</button>
</div>
</div>
<div class="flex-col-c p-t-70">
<span class="txt1 p-b-17">
اکانت ندارید ؟
</span>
<a href="#Url.Action("Register","Home")" class="txt2">
ثبت نام
</a>
</div>
</form>
</div>
</div>
</div>
<div id="dropDownSelect1"></div>
<script src="~/Assets/LoginRegister/js/main.js"></script>
<script src="~/Assets/js/Ajax/UserLoginRegister.js"></script>
HTML tags run correctly and there is no problem with this.
I get username and password from the user and check it in the database, Whether this username exists or not?
I've done this with AJAX
This is My JavaScript Code :
Note : Do not pay attention to the Add function , This function is for Registration page
function Add() {
var userEmail = $('#UserEmail').val();
var userMobile = $('#UserMobile').val();
var userPassword = $('#UserPassword').val();
var url = "UserRegister";
$.post(url, { email: userEmail, mobile: userMobile, password: userPassword }, function (data) {
if (data.message != "ثبت نام شما به درستی انجام شد") {
$('#ModalFooterActive').hide();
$('#SmallNote').hide();
}
else {
$('#ModalFooterActive').html('<button class="btn btn-sm btn-primary" type="button" id="btnActiveEmail">ارسال ایمیل فعالسازی</button>');
$('#SmallNote').show();
}
$("#MessageModalAjax").show();
$("#ModalMessageBody").html(data.message);
$("#btnActiveEmail").click(function () {
$(this).css("display", "none");
ActiveEmail(data.userActiveEmail, userEmail);
});
});
function ActiveEmail(userActiveEmail, userEmail) {
if (userActiveEmail == null) {
return false;
}
else {
var url = "VerifyEmail";
$.post(url, { UserEmail: userEmail, UserEmailActiveCode: userActiveEmail }, function (data) {
$("#EmailSendMessage").html(data);
});
}
function Login() {
var userEmailLogin = $("#UserEmailLogin").val();
var userPasswordLogin = $("#UserPasswordLogin").val();
var MyUser = { UserValue: userEmailLogin, UserPassword: userPasswordLogin };
$.ajax({
url: "LoginDetails",
data: JSON.stringify(MyUser),
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (data) {
if (data.message == "حساب کاربری شما هنوز فعال نشده است") {
$('#ModalFooterActive').html('<button class="btn btn-sm btn-primary" type="button" id="btnActiveEmail">ارسال ایمیل فعالسازی</button>');
$("#MessageModalLogin").show();
$("#ModalMessageBodyLogin").html(data.Message);
$("#btnActiveEmail").click(function () {
$(this).css("display", "none");
ActiveEmail(data.userEmailActiveCode, userEmailLogin);
});
}
else if (data.message == "ورود با موفقیت انجام شد") {
window.setTimeout(function () {
window.location.href = SetURLLogin();
}, 5000);
}
else {
$("#ModalMessageBodyLogin").html(data.Message);
}
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
In these codes, the Add function works correctly, which means JavaScript code is not bad, and Visual Studio executes it correctly.
My problem is so weird!!!
When I run the program by Breakpoint, the program works correctly and receives the information I need from the database But inside the browser console writes: Login is not defined at HTMLButtonElement.onclick.
If it does not find the Login function, how does the database bring information???!!!
Finally: My problem is that Function Login does not run correctly
Thank you
I am trying to edit and delete a data in Mongo.Collection. I have a document with a number of fields including an email address.
I check while updating the data if email exists just update the email else first create a user with that email using Accounts.createUser and then update the data. Although the data is being updated successfully in the database but showing it using the helpers is not working properly. I am trying to fill the form with the saved values, either form comes half-filled, or completely-filled(usually in the first edit attempt) or completely empty. I cannot understand the reason behind this beviour.
The form template
<template name="addUnit">
<div class="modal fade" id="addUnitModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">{{#if isEdit}}Edit {{else}}Add {{/if}}Unit</h4>
</div>
{{#if tenantError}}
<div class="alert alert-danger" role="alert">{{tenantError}}</div>
{{/if}}
<form class="frmUnit" id="frmUnit">
<div class="modal-body">
<input class="form-control" type="text" placeholder="Unit Name" name="unitName" value="{{selectedUnit.unitName}}"/>
<input class="form-control" type="number" placeholder="Number of Residents" name="residents" value="{{selectedUnit.residents}}"/>
<input class="form-control" type="number" placeholder="Area sqft." name="area" value="{{selectedUnit.area}}"/>
<input class="form-control" type="text" placeholder="Primary Tenant" name="primaryTenant" value="{{selectedUnit.primaryTenant}}"/>
<input class="form-control" type="email" name="tenantEmail" placeholder="Tenant's Email" value="{{selectedUnit.tenantEmail}}"/>
<input class="form-control" type="password" name="tenantPassword" placeholder="Tenant's Password"/>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
{{#if isEdit}}
<button type="submit" class="btnEditUnit btn btn-primary">Edit Unit</button>
{{else}}
<button type="submit" class="btnAddUnit btn btn-primary">Add Unit</button>
{{/if}}
</div>
</form>
</div>
</div>
</div>
</template>
Helpers
Template.addUnit.helpers({
isEdit: function() {
return Session.get('isEdit');
},
tenantError: function(){
return Session.get('tenantError');
},
selectedUnit: function(){
return Session.get('selectedUnit');
}
});
Events
Template.addUnit.events({
"submit .frmUnit": function(event){
event.preventDefault();
var form = event.target;
if(!Session.get('isEdit')){
console.log('adding');
Meteor.call('addUnit',
Session.get('selectedBuilding')._id,
{
unitName: form.unitName.value,
primaryTenant: form.primaryTenant.value,
tenantEmail: form.tenantEmail.value,
tenantPassword: form.tenantPassword.value,
residents: form.residents.value,
area: form.area.value
}, function(error, result) {
console.log(error, result);
if(!error){
$('#frmUnit')[0].reset();
$('#addUnitModal').modal('hide');
Session.set('tenantError', null);
}else{
Session.set('tenantError', error.reason);
}
});
}else{
console.log('editing');
Meteor.call('editUnit',Session.get('selectedUnit')._id,{
unitName: form.unitName.value,
primaryTenant: form.primaryTenant.value,
residents: form.residents.value,
area: form.area.value,
tenantEmail: form.tenantEmail.value,
tenantPassword: form.tenantPassword.value
}, function(error, result) {
if(!error) {
$('#frmUnit')[0].reset();
$('#addUnitModal').modal('hide');
}else{
Session.set('tenantError', error.reason);
}
});
}
}
});
Edit unit on the server
editUnit: function(unitId, unit){
//if the email entered already exists update the email and password
var updatedTenant = Accounts.findUserByEmail(unit.tenantEmail);
if(updatedTenant){
if(unit.tenantPassword && unit.tenantPassword !== ""){
Accounts.setPassword(updatedTenant._id, unit.tenantPassword);
}
Units.update({_id: unitId},
{
$set :{
unitName:unit.unitName,
primaryTenant:unit.primaryTenant,
residents: unit.residents,
area: unit.area,
tenantEmail: unit.tenantEmail
}
});
}else{
//if email doesn't exist already, create a new user first
var newUserId = Accounts.createUser(
{
email: unit.tenantEmail,
password: unit.tenantPassword,
profile:{
firstname: unit.primaryTenant,
lastname:"",
phone:"",
isTenant:true
}
});
if(newUserId){
Units.update({_id: unitId},
{
$set :{
unitName:unit.unitName,
primaryTenant:unit.primaryTenant,
residents: unit.residents,
area: unit.area,
tenantEmail:unit.tenantEmail
}
});
}
}
},
Session.get('selectedUnit') is being set from a different click handler, which displays the form. The value is being set correctly I can see that by logging it to the console.
'isEdit' is also being set from a click handler of a different template.
I have other forms working with the same approach, but they don't have Account creation and validation in them. Is it because of that?
Edit
Template.owner.events({
"click .editUnit":function(){
Session.set('isEdit', true);
Session.set('selectedUnit', this);
}
});
{{#each buildingUnits}}
<tr>
<td>
{{unitName}}
</td>
<td>
<span class= "editUnit list-icon glyphicon glyphicon-edit" data-target="#addUnitModal" data-toggle="modal" aria-hidden="true" style="padding-right: 4px;"></span>
<span class= "deleteUnit list-icon glyphicon glyphicon-remove" aria-hidden="true"></span>
</td>
</tr>
{{/each}}
I have tried to log this onto the console, I am getting the correct result, just after the two lines I tried to get the session back using Session.get('selectedUnit') and tried logging it to console, this also gives me the correct result, which means session is being successfully set.
I'm working on a website where I have implemented Bootstrap's modal component as a login form.
I have my login script working correctly (tested without the modal), however, it obviously is not able to display errors as the modal closes before any errors are displayed. My best bet to get the errors displaying is to use AJAX. I've attempted implementing AJAX into it, but seem to be failing miserably (it's not something I'm familiar with).
Here's the code I've tried so far:
index.php
<script type="text/javascript">
function login(username, password, callback) {
var xhr = new XMLHttpRequest();
xhr.open("POST", "login.php", true);
xhr.responseType = "json";
xhr.onload = function() {
var data = xhr.response;
if (data["status"] === "failure") {
callback({
"errorCode": data["errorCode"],
"errorMessage": data["errorMessage"]
});
} else {
callback(null, data["redirect"]);
$("#error").append(errorMessage);
}
};
xhr.send(JSON.stringify({
"username": username,
"password": password
});
}
</script>
--- // ---
<div id="loginModal" class="modal fade" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<div class="loginForm">
<div id="error"></div>
<form id="login" action="index.php" method="post">
<div class="input-container">
<label for="username">Email or Username</label>
<input type="text" name="username" required class="form-control"/>
</div>
<div class="input-container">
<label for="password">Password</label>
<input type="password" name="password" required class="form-control"/>
</div>
<div class="input-container">
<input type="checkbox" name="remember" value="true" id="remember" />
<label for="remember">Remember me</label>
</div>
<div class="submit-container">
<button type="submit" class="btn btn-primary btn-login">SIGN IN</button>
</div>
</form>
</div>
<h2><span>or</span></h2>
<div class="social-signin">
Sign in with Facebook
Sign in with Google+
</div>
</div>
<div class="modal-footer">
<p>Need an account? Sign up here.</p>
</div>
</div>
</div>
</div>
login.php
--- // ---
login_complete($user_id);
$output = [];
$output["status"] = "success";
echo json_encode($output);
exit;
} else {
echo json_encode(array("status" => "failure", "errorCode": $result[0], "errorMessage": $ERRORMSGS[$result[0]]));
}
My question is, how can I properly implement AJAX into my Bootstrap modal login form, to successfully display error messages (such as "Incorrect username and/or password")? At the moment, no error is displayed and the user isn't authenticated (it just goes back to index.php).
Any help is greatly appreciated.
Here's something to get you started: this is basically what I use and is pretty similar to what you have. It uses ajax to send the form to login.php, which returns a json response. The magic happens in login.html and is really quite easy: just add a messages div to the modal, and then target that with jQuery to add your messages and appropriate Bootstrap alert classes.
login.html
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0">
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<!--[if lt IE 9]>
<script src="//oss.maxcdn.com/libs/html5shiv/r29/html5.min.js"></script>
<script src="//oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<button class="btn btn-primary" data-toggle="modal" data-target="#myModal">Login</button>
<div class="modal fade" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<form id="form" role="form">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title">Login</h4>
</div>
<div class="modal-body">
<div id="messages"></div>
YOUR FORM ELEMENTS HERE
Username: <input type="text" name="username">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Login</button>
</div>
</form>
</div>
</div>
</div>
</div>
<script src="http://code.jquery.com/jquery.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script>
$('#form').submit(function(e) {
var form = $(this);
var formdata = false;
if(window.FormData){
formdata = new FormData(form[0]);
}
var formAction = form.attr('action');
$.ajax({
type : 'POST',
url : 'login.php',
cache : false,
data : formdata ? formdata : form.serialize(),
contentType : false,
processData : false,
dataType: 'json',
success: function(response) {
//TARGET THE MESSAGES DIV IN THE MODAL
if(response.type == 'success') {
$('#messages').addClass('alert alert-success').text(response.message);
} else {
$('#messages').addClass('alert alert-danger').text(response.message);
}
}
});
e.preventDefault();
});
</script>
</body>
</html>
login.php
<?php
$success = true;
if($success == true) {
$output = json_encode(array('type'=>'success', 'message' => 'YAY'));
} else {
$output = json_encode(array('type'=>'error', 'message' => 'WHOOPS'));
}
die($output);
If you want to implement AJAX, the button which does the submission has a type of submit and fires the submit event on the form, which will not let your code even reach the function that does the AJAX call.
Instead, you could change the type of the button from submit to button, and add the following handler to trigger when the form submits:
$('#login').submit(function(){
//prepare your username, password and callback
login(username, password, callback);
});