Bootstrap Modal Login with AJAX - javascript

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);
});

Related

Setting Events for similar fields in HTML using JQuery, and Javascript

I am not really good at the HTML world, and I'm not even sure how to debug this one. Anyway, I have an ASP.NET core App. My issue is in a CSHTML view. It is a timeclock system. User logs time against an existing job.
I have an Index.cshtml that is working. It will verify a JobNumber to make sure it exists in the database. And if the user enters a partial number and hits F3, it pops up a modal window (I'm using Bootstrap 5) to allow them to select from a list.
The problem is, the user wants to add more Job numbers. So, they can clock time against up to five Jobs at once. So, I am creating new fields, and naming them JobNumber2, JobNumber3, etc.
What I want to do is reuse the existing scripts to add the verification and popup functionality to each of the new fields.
I have tried several different things based on a half a dozen tutorials out there, but I am just not good enough at Javascript and JQuery to know how to do this.
Any help is appreciated!
[EDIT]
Ruikai Feng's answer shows how to match the first function, but that one calls validateJobNumber(jobNumber), and the result will update a field -- again based on the same pattern. So, now it updates: jobNumberValidationMessage -- but I need it to update the correct jobNumberValidationMessage depending on which JobNumber field got matched in the first half of this. IDK, maybe these could be combined into one function? I'm not sure. But how do I take what I matched with id^='JobNumber to figure out which jobNumberValidationMessage to update (ie jobNumberValidationMessage2, jobNumberValidationMessage3, etc) ;
------------ END EDIT
Here's the code I have that is working, but needs changed:
#using Microsoft.AspNetCore.Http
#using Microsoft.AspNetCore.Http.Extensions
#model dynamic
<!DOCTYPE html>
<html>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-10">
<!-- Clock-In Header -->
<h3>
<img class="logo large" src="logo-png-transparent.png")"
alt="Logo" width="100" height="100"> Add Job Number(s) to Track Time for: #Model.Employee.Name
</h3>
<hr /> <!-- Ruler Line for Separation -->
<!-- End Clock-In Header -->
<!-- Clock-In Form -->
<div class="row">
<div class="col-1 col-md-12 offset-md-0">
<div class="card">
<div class="card-body">
<form asp-action="ClockInBegin" method="post">
<label for="JobNumber" class="col-7 col-md-2 col-form-label text-md-right">Job Number</label>
<div class="col-md-4">
<input type="text" id="JobNumber" name="JobNumber" class="form-control" onkeydown="jobNumberKeyDown(this)" onblur="jobNumberBlur(this)" value="#Model.TrackingItem.JobNumber">
<div class="col-md-8">
<span id="jobNumberValidationMessage"></span>
</div>
</div>
</div>
<div class="form-group row">
<div class="form-check form-switch col-4 align-with-label">
<input class="form-check-input" type="checkbox" value="" id="MultipleCheck">
<label class="form-check-label" for="MultipleCheck">Multiple</label>
</div>
</div> <!-- End form-group row -->
<div>
<button type="submit" class="btn btn-primary w-100">Start Clock</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- Clock-In Modal Pop-up -->
<div class="modal fade" id="myModal">
<div class="modal-dialog modal-dialog-scrollable">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Select Job Number</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<select id="jobNumberSelect" class="form-control">
<option value="">Select Job Number</option>
<!-- Dynamic options generated via JavaScript or ajax -->
</select>
</div>
<div class="modal-footer">
<button type="button" id="CANCEL"class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="button" id="OK" class="btn btn-primary" data-bs-dismiss="modal">OK</button>
</div>
</div>
</div>
<!-- End Clock-In Modal Pop-up -->
</div>
</div>
</div>
</div>
<script>
$(document).ready(function () {
$("#JobNumber").blur(function () {
var jobNumber = $(this).val();
validateJobNumber(jobNumber);
});
$("#JobNumber").keydown(function (event) {
if (event.key === "F3") {
event.preventDefault();
if (event.target.value.length >= 2) {
// Open the modal
$('#myModal').modal('show');
// Populate the select options
$.ajax({
type: "GET",
url: "#Url.Action("GetJobNumbers")",
data: { searchTerm: event.target.value },
dataType: "json",
success: function (data) {
$("#jobNumberSelect").empty();
$.each(data, function (index, item) {
$("#jobNumberSelect").append("<option value='" + item + "'>" + item + "</option>");
});
$("#jobNumberSelect").val("..."); // clear the initial value. Make them select it
//set prompt in first cell of select
$("#jobNumberSelect").prepend("<option value=''>Select Job Number</option>");
$("#myModal").modal("show");
}
});
}
}
});
$("#jobNumberSelect").change(function () {
$("#JobNumber").val($(this).val());
});
$("#OK").click(function () {
$("#JobNumber").val($("#jobNumberSelect").val());
validateJobNumber(); // call the validation
$("#myModal").modal("hide");
});
$('#MultipleCheck').change(function () {
if (this.checked) {
$(this).val(true);
$('[name="MultipleCheck"]:hidden').val(true);
$("#hiddenFields").show();
}
else {
$(this).val(false);
$("#hiddenFields").hide();
}
})
}); // end Document.Ready functions
function validateJobNumber() {
var jobNumber = $("#JobNumber").val();
$.ajax({
type: "POST",
url: "#Url.Action("VerifyJobNumber")",
data: { jobNumber: jobNumber },
dataType: "text",
success: function (respdata) {
// alert(respdata);
const obj = JSON.parse(respdata);
var rmessage = obj.message;
$("#jobNumberValidationMessage").text(rmessage);
$("#jobNumberValidationMessage").css("color", "green");
}
});
}
</script>
</body>
</html>
if you have mutipule inputs like:
<input type="text" id="JobNumber1" name="JobNumber1" class="form-control"  value="1">
<input type="text" id="JobNumber2" name="JobNumber2" class="form-control"  value="2">
<input type="text" id="JobNumber3" name="JobNumber3" class="form-control"  value="3">
and you want validate the value on blur ,just try as below:
$("[id^='JobNumber']").blur(function(e)        
{             
var jobnumber=$(this).val();             
$.ajax({               
 type: "POST",               
 url: "#Url.Action("VerifyJobNumber")",               
 data: { "jobNumber": jobnumber },               
 dataType: "text",                
success: function (respdata) {                     
alert(respdata);                                  
 }            
});        
});
With a controller :
[HttpPost]       
public IActionResult VerifyJobNumber(string jobNumber)        
{            
return Ok(jobNumber);        
}
The result:

In a popup, how do I add a file to the ajax submit and stay in the popup for the results of the backend?

I found setting the title a bit awkward, it's complicated to exaplain in 1 sentence.. Some of our pages use popups where the user can fill in fields and then send. This is based on some Kallyas stuff and works fine with just text fields. After submitting, user staus on the same page, the form stays open and in it the message appears that the form has been sent (or not). There is also recaptcha handling in it.
Now I need to give the possibility to upload a file and this is where I am stuck. There is a .js file that does the handling. It picks up the form and does a ajax submit. I can see the form field of my input type="file" here, but with a fakepath/empty. If, in this javascript I try to append the file to the form I can submit, but the the backend says the form field is not there.
First, let me share the code.
The form :
<!-- Application form pop-up element content -->
<div id="application_panel" class="mfp-hide contact-popup">
<div class="contact-popup-panel">
<div class="container-fluid">
<div class="row">
<div class="col-md-12 col-sm-12">
<!-- Application form pop-up element -->
<div class="applicationForm pop-up-form" style="padding:50px;">
<!-- Title -->
<div id="jatitlewrapper">
<h3 class="m_title m_title_ext text-custom contact-popup-title c_title">
Some title
</h3>
<h4 class="tbk__subtitle fw-thin dark">
</h4>
</div>
<form id="appform" action="#request.projectname#/scripts/ajax/save/processform.cfm" method="post" class="contact_form row mt-40" enctype="multipart/form-data">
<div id="jafldwrapper">
<div class="col-sm-6 kl-fancy-form">
<input type="text" name="firstname" id="cf_firstname-pop-up" class="form-control" placeholder="Vul hier je voornaam in" value="" tabindex="1" required>
<label class="control-label">
VOORNAAM
</label>
</div>
<div class="col-sm-6 kl-fancy-form">
<input type="text" name="lastname" id="cf_lastname-pop-up" class="form-control" placeholder="Type je achternaam in" value="" tabindex="1" required>
<label class="control-label">
ACHTERNAAM
</label>
</div>
<div class="col-sm-12 kl-fancy-form">
<input type="text" name="place" id="cf_place-pop-up" class="form-control" placeholder="Voeg een onderwerp toe" value="" tabindex="1" required maxlength="78">
<label class="control-label">
WOONPLAATS
</label>
</div>
<div class="col-sm-12">
<label class="label_upl">
UPLOAD FILE
</label>
<input id="resume" style="padding-bottom:15px;" type="file" name="resume" id="cf_subject-pop-up" class="" placeholder="" value="" tabindex="1">
</div>
<cfif Application.isProductionURL>
<div class="col-sm-12" style="margin-left:15px;">
<div class="g-recaptcha" data-sitekey="somesitekey"></div>
</div>
<div class="col-sm-6">
<!-- Contact form send button -->
<button id="submitbtn" class="btn btn-fullcolor" type="submit" onClick="$('.g-recaptcha-response').attr('name','g_recaptcha_response');">
Send
</button>
</div>
<cfelse>
<div class="col-sm-6">
<!-- Contact form send button -->
<button id="submitbtn" class="btn btn-fullcolor" type="submit">
Send
</button>
</div>
</cfif>
<div class="col-sm-6" style="text-align:right;">
<button class="btn btn-fullcolor" type="button" onClick="closePopup();">
Cancel
</button>
</div>
</div>
<input type="hidden" name="fjobuuid" id="fjobuuid" value="">
</form>
</div>
<!--/ Application form pop-up element -->
</div>
<!--/ col-md-12 col-sm-12 -->
</div>
<!--/ .row -->
</div>
<!--/ .container -->
</div>
<!--/ .contact-popup-panel -->
<button title="Sluiten (Esc)" type="button" class="mfp-close">×</button>
</div>
<!--/ Application form pop-up element content -->
Some javascript for the popup to show :
window.onload = function() {
$('.abutton').magnificPopup({
closeBtnInside: true,
type: 'inline',
preloader: false
});
}
The standard js that handles the sumbit and works with all text fields on the form :
if(typeof($('.applicationForm form, .applicationForm.pop-up-form form, .contact_form form')) != 'undefined') {
$.each($('.applicationForm form, .applicationForm.pop-up-form form, .contact_form form'), function(index, el) {
var cform = $(el),
cResponse = $('<div class="cf_response col-sm-12"></div>');
cform.prepend(cResponse);
cform.h5Validate();
cform.submit(function(e) {
$('#g-recaptcha-response').attr('name','g_recaptcha_response');
e.preventDefault();
if(cform.h5Validate('allValid')) {
cResponse.hide();
$.post(
$(this).attr('action'),
cform.serialize(),
function(data){
console.log(data);
cResponse.html(data).fadeIn('fast');
if(data.match('success') != null) {
cform.get(0).reset();
}
}
); // end post
}
return false;
});
});
}
The backend does some handling of the fields and then produces a message, which is then visible in the popup :
<cfoutput><div class="alert alert-success alert-dismissible" role="alert"><p>Message sent, thank you</p></div></cfoutput>
or a message with class alert-danger if something went wrong.
Now I tried adding the file field 'resume' to the form by adding a cform.append, right after the cform.submit :
var files = $("#resume")[0].files;
for (var i = 0; i < files.length; i++) {
cform.append(files[i].name, files[i]);
}
It does loop and seems to append the file.
But the backend says form.resume is not there.
I tried writing my own submit :
$("#submitbtn").on("click", function(e) {
var form = $("#appform");
var params = form.serializeArray();
var files = $("#resume")[0].files;
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
formData.append(files[i].name, files[i]);
}
$(params).each(function (index, element) {
formData.append(element.name, element.value);
});
$.ajax({
type: "POST",
url: $(form).prop("action"),
data: formData,
processData: false,
error : function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);}
,
success : function(data){
console.log(data);
}
});
})
Then the backend has all fields needed, including the actual file. But then I don't know how to integrate staying on the same url with the popup still in place and the message from the backend in the right place.
Then I tried changing the button type from sumbit to button, but then it won't let me send the file with the ajax call.
$.ajax({
type: "POST",
url: 'proctname//scripts/ajax/save/processform.cfm',
data: formData,
processData: false,
contentType: false,
error : function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);}
,
success : function(data){
var obj = $.parseJSON( data );
console.log(data);
}
});
Giving form field 'resume' is undefined. Apparently it needs to be a form submit.
Can I add the file field 'resume' to the standard code after the cform.submit, keep page and popup open, have the message handling etetc and if so, how?

How to display error on the same page when an error is returned by a form?

I have built a login form using below code.
I am using a CGI version CGIDEV2 native to IBMi series. I am Validating the userid and password in the flower.cgi program. If the userid and password are validated, I am loading another html file to show a table. This works flawlessly.
If the userid and password are wrong, I am returning out of the program without writing anything. This results in a 500 Internal server error.
I want to capture this 500 Internal server error using javascript. I have tried using ajax but was not successful as I have limited understanding of javascript.
What could be the best way to achieve this?
<form method="POST" action="/nature/flower.cgi">
<!-- Username input -->
<div class="form-outline mb-4">
<input type="text" name="userid" id="form3Example3" class="form-control form-control-lg" style="text-transform:uppercase" placeholder="Enter a valid IBMi UserID" />
<label class="form-label" for="form3Example3">IBMi UserID</label>
</div>
<!-- Password input -->
<div class="form-outline mb-3">
<input type="password" name="passwd" id="form3Example4" class="form-control form-control-lg" placeholder="Enter password" />
<label class="form-label" for="form3Example4">Password</label>
<br>
</div>
<div class="d-flex justify-content-between align-items-center">
<!-- Checkbox -->
<div class="form-check mb-0">
<input class="form-check-input me-2" type="checkbox" value="" id="form2Example3" />
<label class="form-check-label" for="form2Example3">Remember me</label>
</div>
Forgot password?
</div>
<div class="text-center text-lg-start mt-4 pt-2">
<button type="submit" class="btn btn-primary btn-lg" style="padding-left: 2.5rem; padding-right: 2.5rem;">Login</button>
</div>
</form>
You can't capture an error from a URL the browser is navigating to.
The only way you could would be if you replaced the normal form submission with Ajax (in which the request is made and the response processed with JavaScript).
Generally speaking, if you were going to do that you would also want to rewrite the CGI program so it output structured data (e.g. as JSON) instead of semantic data (HTML).
It would not be a particularly small undertaking. You said you had tried it, which probably gives you some idea of the scope of it (i.e. far outside the scope of a Stackoverflow question).
A more sensible approach would almost certainly be to track down the cause of the 500 error and change the CGI program so it would capture it itself.
yes, the fetch api in javascript can post form data to your CGI program and check for the 500 response code. Then the web page can either display an error message or run the form.submit() method to actually submit the form up to the server.
Here is PHP and javascript code that simulates the whole thing. Should work similar with CGI. The key is you change the form submit button from type 'submit' to type 'button'. That way, clicking the submit button can run javascript code instead of the form being submitted to the server.
<?php
// site/tester/php/submit-form.php
header("Content-type: text/html; charset:utf-8;");
?>
<?php
$userid = isset($_POST["userid"]) ? $_POST["userid"]: '' ;
$passwd = isset($_POST["passwd"]) ? $_POST["passwd"]: '' ;
$remember = isset($_POST["remember"]) ? $_POST["remember"]: 'off' ;
if ( strtolower($userid) == 'alex')
{
http_response_code( 500 );
echo "$userid - invalid user name";
exit ;
}
?>
<head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row mt-3">
<div class="col-auto">
<h1>submit form demo</h1>
</div>
</div>
</div>
<div class="container">
<div class="row mt-3">
<div class="col-4">
<form method="POST" id="main-form" action="./index.php">
<!-- Username input -->
<div class="form-outline mb-4">
<input type="text" name="userid" id="userid"
class="form-control form-control-lg"
value="<?= $userid ?>"
style="text-transform:uppercase" placeholder="Enter a valid IBMi UserID" />
<label class="form-label" for="userid">IBMi UserID</label>
</div>
<!-- Password input -->
<div class="form-outline mb-3">
<input type="password" name="passwd" id="passwd" class="form-control form-control-lg"
placeholder="Enter password" />
<label class="form-label" for="passwd">Password</label>
<br>
</div>
<div class="d-flex justify-content-between align-items-center">
<!-- Checkbox -->
<div class="form-check mb-0">
<input class="form-check-input me-2" type="checkbox"
<?= ($remember == 'on' ? 'checked' : '' ) ?>
name="remember" id="form2Example3" />
<label class="form-check-label" for="form2Example3">Remember me</label>
</div>
Forgot password?
</div>
<div class="text-center text-lg-start mt-4 pt-2">
<button id="login-button" type="button" class="btn btn-primary btn-lg"
style="padding-left: 2.5rem; padding-right: 2.5rem;">
Login</button>
</div>
</form>
</div>
</div>
<div id="login-errmsg-collapse" class="collapse row mt-3">
<div class="alert alert-warning" role="alert">
<p id="login-errmsg">Invalid login. User name does not exist.</p>
</div>
</div>
</div>
<div class="container">
<div class="row mt-3">
<div class="col-auto">
<p>userid: <?= $userid ?></p>
<p>passwd: <?= $passwd ?></p>
<p>remember: <?= $remember ?></p>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
crossorigin="anonymous"></script>
<script src="./app.js"></script>
</body>
// ./submit-form/app.js
// enable the submit button click handler.
{
const elem = document.getElementById('login-button');
elem.addEventListener('click', event =>
{
login_click();
});
}
// -------------------------------- login_errmsg_show ---------------------
function login_errmsg_show( respText )
{
// show the response message in the bootstrap collapse alert box.
{
const elem = document.getElementById('login-errmsg') ;
elem.textContent = respText ;
}
const myCollapse = document.getElementById('login-errmsg-collapse')
const bsCollapse = new bootstrap.Collapse(myCollapse, {
toggle: false
});
bsCollapse.show( ) ;
}
// -------------------------------- login_click -------------------
async function login_click()
{
const elem = document.getElementById('main-form');
if (elem)
{
const {respText, status} = await webpage_post( ) ;
if ( status != '500')
{
elem.submit();
}
else
{
login_errmsg_show( respText ) ;
}
}
}
// --------------------------------- webpage_post -----------------------
async function webpage_post( )
{
const userid = document.getElementById('userid').value ;
const passwd = document.getElementById('passwd').value ;
const remember = 'on' ;
const url = "./index.php";
const params = { userid, passwd, remember } ;
const query = object_toQueryString(params);
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: query
});
const respText = await response.text();
const status = response.status ;
console.log( respText ) ;
return {respText, status} ;
}
// ------------------------- object_toQueryString ------------------------
function object_toQueryString(obj)
{
const qs = Object.keys(obj)
.map((key) => encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]))
.join('&');
return qs;
}

How to fetch and display selected value into <select2> tag in my Edit Form using ajax (codeigniter)

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);

Submit change password form in bootstrap modal through ajax

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();

Categories