JS ajax event to by input change - javascript

I would like to have this code so I because if I go into the other input field, the other is updated
Or secound better input change
// on click search results...
$(document).on("touchend", "#ean", function() {
var value = $("#ean").val();
if (value.length != 0) {
//alert(99933);
searchData(value);
} else {
$('#search-result-container').hide();
}
});
// This function helps to send the request to retrieve data from mysql database...
function searchData(val) {
$('#search-result-container').show();
$('#search-result-container').html('<div><img src="app/ajax-artstk/preloader.gif" width="50px;" height="50px"> <span style="font-size: 20px;">Please Wait...</span></div>');
$.post('app/ajax-artstk/controller.php', {
'ean': val
}, function(data) {
if (data != "")
$('#search-result-container').html(data);
else
$('#search-result-container').html("<div class='search-result'><div class=\"alert alert-danger\" role=\"alert\">No Result Found...</div></div>");
}).fail(function(xhr, ajaxOptions, thrownError) { //any errors?
alert(thrownError); //alert with HTTP error
});
}
<form action="#" method="POST" autocomplete="off">
<div class="form-group">
<input type="hidden" name="ausgang">
<div class="row">
<div class="col-md-2">
<label class="control-label"></label>
</div>
</div>
<hr>
<div class="row">
<div class="col-md-2">
<label for="ean" class="control-label">EAN</label>
</div>
<div class="col-md-4">
<input type="text" name="ean" class="form-control" id="ean" value="" maxLength="100" autofocus>
<div id="search-result-container" style="border:solid 0px #BDC7D8;display:none; "></div>
</div>
</div>
<div class="row">
<div class="col-md-2">
<label for="stueck" class="control-label">- Stück</label>
</div>
<div class="col-md-2">
<input type="text" name="stk" class="form-control" id="stk" value="" maxLength="3">
</div>
</div>
<hr>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="submit" class="btn btn-success">Entnehmen</button>
<button type="reset" class="btn btn-danger">S</button>
<!-- PRINTBUTTON -->
</div>
</div>
</div>
<!-- END form-group -->
</form>
who can help me please who the very nice of you have already tried everything so far
I want to use that via Android and Windows 7 Firefox browser.
I thank you very much for the help that I get I would like to ask to send any links where it is poorly explained

<script>
// on click search results...
$('body').on('change', '#ean', function() {
var value = $("#ean").val();
if (value.length != 0) {
//alert(99933);
searchData(value);
} else {
$('#search-result-container').hide();
}
});
// This function helps to send the request to retrieve data from mysql database...
function searchData(val){
$('#search-result-container').show();
$('#search-result-container').html('<div><img src="app/ajax-artstk/preloader.gif" width="50px;" height="50px"> <span style="font-size: 20px;">Please Wait...</span></div>');
$.post('app/ajax-artstk/controller.php',{'ean': val}, function(data){
if(data != "")
$('#search-result-container').html(data);
else
$('#search-result-container').html("<div class='search-result'><div class=\"alert alert-danger\" role=\"alert\">No Result Found...</div></div>");
}).fail(function(xhr, ajaxOptions, thrownError) { //any errors?
alert(thrownError); //alert with HTTP error
});
}
</script>

Related

Google invisible reCaptcha is only working in Incognito mode

I have a Google reCAPTCHA setup on my contact form in my website.
and i'm trying to test it in both localhost and server as well but recaptcha is only working in incognito mode .
without capturing reCAPTCHA mails are sending .
Here my problem is grecaptcha.execute(); is not executing, Please suggest solution for this.
$("#cont_msg").keypress(function (e) {
var key = e.which;
if (key == 13) {
// the enter key code
$("#contact_form_submit").click();
return false;
}
});
$(
".app_form_wrapper .apps_input input, .app_form_wrapper .apps_input textarea"
).keypress(function () {
$(this).parent().removeClass("error");
});
function sendMail() {
var co_name = $("#cont_name").val();
var co_email = $("#cont_email").val();
var co_phone = $("#cont_phone").val();
var co_company = $("#cont_company").val();
var co_message = $("#cont_msg").val();
let data = {
username: co_name,
useremail: co_email,
userphone: co_phone,
usercompany: co_company,
usermessage: co_message,
};
$("#loading").show();
$("#contact_form_submit").hide();
$.ajax({
type: "POST",
url: "contact_ajaxmail.php",
data: data,
success: function (contact) {
//grecaptcha.execute();
$("#loading").hide();
$("#contact_form_submit").show();
var i = contact.split("#");
if (i[0] == "1") {
$("#cont_name").val("");
$("#cont_email").val("");
$("#cont_phone").val("");
$("#cont_company").val("");
$("#cont_msg").val("");
$("#contact_err").html(i[1]);
$(".app_form_wrapper .apps_input").addClass("success");
setTimeout(function () {
$(".app_form_wrapper .apps_input").removeClass("success");
$(".app_form_wrapper .apps_input").removeClass("error");
$("#cont_email").parent().removeClass("error");
}, 2500);
} else {
$("#cont_name").val(data.username);
$("#cont_email").val(data.useremail);
$("#cont_phone").val(data.userphone);
$("#cont_company").val(data.usercompany);
$("#cont_msg").val(data.usermessage);
$("#contact_err").html(i[1]);
$(
".app_form_wrapper .apps_input input, .app_form_wrapper .apps_input textarea"
).each(function () {
if (!$(this).val()) {
$(this).parent().addClass("error");
} else {
if (i[0] == 3) {
$("#cont_email").parent().addClass("error");
} else {
$(this).parent().addClass("error");
}
$(this).parent().removeClass("error");
}
});
}
},
});
}
**My form**
Here iam trying to send mails for entered email
<!DOCTYPE html>
<html lang="en">
<!-- BEGIN HEAD -->
<head>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<form class="app_form_wrapper" role="form" >
<div class="col-lg-6 text-left">
<div class="form-group apps-pulldown-20">
<div class="apps_input">
<input type="text" class="form-control" id="cont_name"placeholder="Name">
</div>
</div>
<div class="form-group apps-pulldown-20">
<div class="apps_input">
<input type="text" class="form-control" id="cont_email" placeholder="Email">
</div>
</div>
<div class="form-group apps-pulldown-20">
<div class="apps_input">
<input type="tel" class="form-control" id="cont_phone" placeholder="Phone Number" minlength="10" maxlength="15">
</div>
</div>
</div>
<div class="col-lg-6">
<div class="form-group apps-pulldown-20">
<div class="apps_input">
<input type="text" class="form-control" id="cont_company" placeholder="Company">
</div>
</div>
<div class="form-group apps-pulldown-20">
<div class="apps_input">
<textarea rows="10" class="form-control" id="cont_msg" placeholder="Message"></textarea>
</div>
</div>
</div>
<div class="col-lg-12">
<div class="g-recaptcha"
data-sitekey="Site_key"
data-callback="sendMail"
data-size="invisible">
</div>
<p>
This site is protected by reCAPTCHA and the Google
Privacy Policy and
Terms of Service apply.
</p>
<a class="btn btn-default btn-lg contact_btn" id="contact_form_submit">Send</a>
<a class="btn btn-default btn-lg contact_btn" id="loading" style="display: none;">Sending...</a>
<p class="input_error"id="contact_err" style="color:#FF6666;position:absolute;font-size:14px;font-weight: 500;letter-spacing: 0.5px;bottom: 10px;left: 0;right: 0;">
</p>
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
$("#contact_form_submit").on("click", function () {
var co_name = $("#cont_name").val();
var co_email = $("#cont_email").val();
var co_phone = $("#cont_phone").val();
var co_company = $("#cont_company").val();
var co_message = $("#cont_msg").val();
if (
co_name != "" &&
co_email != "" &&
co_phone != "" &&
co_company != "" &&
co_message != ""
) {
grecaptcha.execute();
} else {
$("#loading").hide();
$("#contact_form_submit").show();
$("#contact_err").html("Please fill all the fields !!!!");
}
});
})
</script>
</body>
</html>
Captcha needs two things to make it work properly
Client side code in Javascript, this you have done by looks of it properly.
Server side code, without implementing server side code the captcha is useless as bots will just post straight to your PHP form without having to enter a captcha! This is your missing piece based on your comments.
See
https://developers.google.com/recaptcha/intro
Notice it says you need to do 2 steps, 1 client side, 2 verify the response:
https://developers.google.com/recaptcha/docs/verify
Google returns loads results but this seems to be an up to date article
https://phppot.com/php/php-contact-form-with-google-recaptcha/
Google implementing google captcha php

AntiforgeryToken generation from using #Ajax.BeginForm()

I have an issue in generating anti-forgery token manually inside ajax methods. So my question If I used ajax.beginform(), does it generate a token like the #html.beginform? If so, how can I use it with my ajax methods?
Kindly ignore the long code in the view. My main concern is with the ajax methods. I posted it to show you the view in case of the suggestion of using the beginForm().
#*#Html.AntiForgeryToken()*#
<hr />
<div class="row">
<div class="col-lg-6">
<label><strong>Month:</strong></label>
</div>
<div class="col-lg-6">
<label>#manning_HQ.Issue_Date</label>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<label><strong>Count:</strong></label>
</div>
<div class="col-lg-6">
<label>#manning_HQ.Count</label>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<label><strong>Location:</strong></label>
</div>
<div class="col-lg-6">
<label>#manning_HQ.Location_Name</label>
</div>
</div>
<hr />
<div class="col-lg-4">
<label>Recruitment Status :</label>
</div>
<div class="col-lg-3">
<select id="recruitment_Status">
<option value="0">
Choose Status
</option>
#foreach (TBL_Recruitment_Status rec in recruitment_Status)
{
<option value="#rec.Rec_Status_ID">
#rec.Status_Name
</option>
}
</select>
</div>
<div class="row">
<div class="col-lg-12">
<label><strong>Issue staff requisition:</strong></label>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<input type="radio" name="Decision" id="_123" value="Accepted" />
Accepted
</div>
<div class="col-lg-6">
<input type="radio" name="Decision" id="_456" value="Rejected" />
Rejected
</div>
</div>
<hr />
<div class="row" id="RejComment" hidden>
<div class="col-lg-6">
<label>Rejected Comment :</label>
</div>
<div class="col-lg-3">
<textarea id="RetainedComment"></textarea>
</div>
</div>
<br />
<div class="modal-footer" id="Save_Dicision" hidden>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="saveDecision(#manning_HQ.Issue_Staff_ID)">Save</button>
</div>
<script>
var DecesionCheck = false;
var rejected = false;
var reason = false;
$(document).ready(function () {
$('input[type=radio][name=Decision]').change(function () {
if ($("input[name='Decision']:checked").val() == 'Accepted') {
$('#RejComment').hide();
$('#Save_Dicision').show();
rejected = true;
}
if ($("input[name='Decision']:checked").val() == 'Rejected') {
$('#RejComment').show();
$('#Save_Dicision').show();
rejected = true;
}
});
});
function saveDecision(ID) {
var Decsion = $('input[name=Decision]:checked').val();
var Reason = $('#recruitment_Status').val();
//var token = $("[name='__RequestVerificationToken']").val();
if (Decsion == "#_123") {
if (DecesionCheck == true) {
var Decsion = $('input[name=Decision]:checked').val();
var optionalComment = $('#OptionalComment').val();
$.ajax({
type: 'POST',
url: '/Staff_Requisition_HQ/Recruitment_Actions',
data: {
// __RequestVerificationToken: token,
Issue_Staff_ID: ID,
Rec_Status_ID: Reason,
OpComment: RetainedComment,
RecDecison: Decsion,
},
success: function (result) {
$('#DescionDetailsPOPUP').modal('hide');
location.reload();
},
fail: function (xhr, textStatus, errorThrown) {
alert('request failed');
}
});
}
}
else {
var Decsion = $('input[name=Decision]:checked').val();
var RetainedComment = $('#RetainedComment').val();
$.ajax({
type: 'POST',
url: '/Staff_Requisition_HQ/Recruitment_Actions',
data: {
//__RequestVerificationToken: token,
Issue_Staff_ID: ID,
Rec_Status_ID: Reason,
Comment: RetainedComment,
RecDecison: Decsion,
},
success: function (result) {
$('#DescionDetailsPOPUP').modal('hide');
location.reload();
},
fail: function (xhr, textStatus, errorThrown) {
alert('request failed');
}
});
}
}
</script>
Here's an example of Ajax.BeginForm from one of my views:
<!-- FORM Atributo -->
#using (Ajax.BeginForm(accionFormulario, "Atributos", new AjaxOptions() { OnSuccess = "onSuccessCreate" }, new { #id = "frmCreate" }))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(model => model.AtributoId)
#Html.HiddenFor(model => model.EmpresaId)
<div class="modal-body">
<div class="row">
// the form inputs ....
</div>
</div>
<div class="modal-footer">
<button class="btn btn-secondary mx-1" type="button" data-dismiss="modal" aria-label="Close">#Global.Cancelar</button>
<button class="btn btn-primary" type="submit"><strong>#Global.Guardar</strong></button>
</div>
}
This generates the AntiForgeryToken as expected:
You can capture it with javascript as you were doing in your view.

POST Ajax for multiple buttons in one form

I am creating one form that has Auth and Login buttons that is planned to handle sending out OTP and checking if OTP is valid respectively below.
I am following this Process a Form Submit with Multiple Submit Buttons in Javascript using below code, but when I get any button, javascript seems to be not working and I can't not get any console.log values. No error on the browser.
otplogin.html
<div id="otplogin">
<form class="form-horizontal" id="getotp" >
{% csrf_token %}
<div class="control-group">
<label class="control-label" for="username">Username</label>
<div class="controls">
<input type="text" id="username" name="username" placeholder="Username">
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" value='auth' class="btn">Auth</button>
</div>
</div>
<div class="control-group">
<label class="control-label" for="otp">OTP</label>
<div class="controls">
<input type="otp" name="otp" id="otp" placeholder="OTP">
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" value='login' class="btn">Login</button>
</div>
</div>
</form>
</div>
<script type="text/javascript">
(function () { //the browser said the '$' as in the linked answer can not be recognized
$("#getotp btn").click(function (ev) {
ev.preventDefault()
if ($(this).attr("value") == "auth") {
console.log("CHECK 1");
$.ajax({
type:'POST',
url:'/getotp2',
data:{
username:$('#username').val()
,csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
},
success: function server_response(response) {
console.log('POST1 success')
}
});
}
else if ($(this).attr("value") == "login") {
console.log("CHECK 2");
$.ajax({
type:'POST',
url:'/otplogin',
data:{
username:$('#username').val(),
otp:$('#otp').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
},
success: function server_response(response) {
console.log('POST2 success')
}
});
}
});
});
</script>
views.py
def otplogin(request):
if request.POST:
otpentered=request.POST.get('otp','')
if otpentered==otp:
return redirect('/main')
return render(request,'esearch/otplogin.html')
def getotp2(request):
logout(request)
username = otp = ''
if request.POST:
username = request.POST.get('username','')
otp = pyotp.TOTP('base32secret3232').now()
OTPEmail('You Auth',username,[],'Your auth is '+otp)
print ('POST'+username)
print ('POST'+otp)
return JsonResponse(json.dumps({'username':username,'otp':otp}),safe=False)
Appreciate any help on this
Your selection is wrong:
(function(){
$("#getotp btn").click(function (ev){...});}
Change to:
$(document).ready(function(){
$(".btn").click(function(ev){...});});
Or
$("#getotp .control-group .controls .btn").click(...

issue in Bootstrap 4 validation on select field

I'm new to jQuery and Bootstrap, I'm using jquery and Bootstrap 4 for validation of my form modal, whenever there is an error it must show the error below the corresponding fields, but in my case the select field gets overwritten by the error and select field disappears but it works fine for input field.
here have a look and if you want to have a close look on image just click on it..
As you can see the select fields get overwritten by the fieldError but it's fine for input field.
here's my jQuery validation code:
$(function(){
setCategorySelect();
$(document).on('shown.bs.modal','#manageItemsModal', function () {
$('#manageItemsModal #btnSubmit').on('click', function(){
if (validateForm()) {
messageSuccess("Very well");
} else {
messageError("Oops!!");
}
});
});
});
function validateForm() {
var validationStatus = true;
if ($('#manageItemsForm #selectedCategory').val().length == 0) {
showFieldError(('#manageItemsForm #selectedCategory'), 'Must not be blank');
if (validationStatus) { $('#manageItemsForm #selectedCategory').focus() };
validationStatus = false;
}
if ($('#manageItemsForm #selectedBrandModel').val().length == 0) {
showFieldError(('#manageItemsForm #selectedBrandModel'), 'Must not be blank');
if (validationStatus) { $('#manageItemsForm #selectedBrandModel').focus() };
validationStatus = false;
}
if ($('#manageItemsForm #serialNo').val().length == 0) {
showFieldError(('#manageItemsForm #serialNo'), 'Must not be blank');
if (validationStatus) { $('#manageItemsForm #serialNo').focus() };
validationStatus = false;
}
if ($('#manageItemsForm #selectedVendor').val().length == 0) {
showFieldError(('#manageItemsForm #selectedVendor'), 'Must not be blank');
if (validationStatus) { $('#manageItemsForm #selectedVendor').focus() };
validationStatus = false;
}
if ($('#manageItemsForm #selectedBranch').val().length == 0) {
showFieldError(('#manageItemsForm #selectedBranch'), 'Must not be blank');
if (validationStatus) { $('#manageItemsForm #selectedBranch').focus() };
validationStatus = false;
}
return validationStatus;
}
function showFieldError(element, message) {
$(element).addClass('is-invalid');
$(element).next().html(message);
$(element).next().show();
}
function clearFieldError(element) {
$(element).removeClass('is-invalid');
$(element).removeAttr('required');
$(element).next().html('');
}
function setCategorySelect() {
var $categorySelect = $('#manageItemsForm #selectedCategory').selectize({
selectOnTab: true,
closeAfterSelect: true,
persist: false,
create: false,
valueField: 'id',
labelField: 'text',
options: [],
preload: true,
onInitialize : function() {
var self = this;
$.ajax({
url: '/assetCategory/search',
type: 'POST',
dataType: 'json',
data: {
searchText: '*'
},
error: function() {
callback();
},
success: function(res) {
self.addOption(res.data);
}
});
},
load: function(query, callback) {
if (query.length <= 2) return callback();
$.ajax({
url: '/assetCategory/search',
type: 'POST',
dataType: 'json',
data: {
searchText: query + "*"
},
error: function() {
callback();
},
success: function(res) {
console.log(res.data);
callback(res.data);
$categorySelect.refreshItems();
},
fail : function() {
callback();
}
});
}
});
}
here's my HTML:
<div class="modal-body">
<form id="manageItemsForm">
<input type="hidden" id="id" name="id">
<div class="row">
<div class="col-4">
<div class="form-group">
<label for="selectedCategory" class="col-form-label"><span class="text-danger">* </span>Category</label>
<select class="form-control" name="selectedCategory" id="selectedCategory"></select>
<div class="invalid-feedback"></div>
</div>
</div>
<div class="col-8">
<div class="form-group">
<label for="selectedBrandModel" class="col-form-label"><span class="text-danger">* </span>Brand & Model</label>
<select class="form-control" name="selectedBrandModel" id="selectedBrandModel"></select>
<div class="invalid-feedback"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-4">
<div class="form-group">
<label for="serialNo" class="col-form-label"><span class="text-danger">* </span>Serial No.</label>
<input type="text" class="form-control" id="serialNo" name="serialNo">
<div class="invalid-feedback"></div>
</div>
</div>
<div class="col-8">
<div class="form-group">
<label for="description" class="col-form-label">Description</label>
<input type="text" class="form-control" id="description" name="description">
<div class="invalid-feedback"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-6">
<div class="form-group">
<label for="selectedVendor" class="col-form-label"><span class="text-danger">* </span>Purchase Vendor</label>
<select class="form-control" name="selectedVendor" id="selectedVendor"></select>
<div class="invalid-feedback"></div>
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="selectedVendor" class="col-form-label"><span class="text-danger">* </span>Purchase Date</label>
<div class="input-group date" data-date-format="dd-M-yyyy">
<input type="text" class="form-control" id="purchaseDate" name="purchaseDate" />
<span class="input-group-text input-group-append input-group-addon"><i class="simple-icon-calendar"></i></span>
</div>
<div class="invalid-feedback"></div>
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="supportTillDate" class="col-form-label"><span class="text-danger">* </span>Support till date</label>
<div class="input-group date" data-date-format="dd-M-yyyy">
<input type="text" class="form-control" id="supportTillDate" name="supportTillDate" />
<span class="input-group-text input-group-append input-group-addon"><i class="simple-icon-calendar"></i></span>
</div>
<div class="invalid-feedback"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-9">
<div class="form-group">
<label for="selectedBranch" class="col-form-label"><span class="text-danger">* </span>Branch</label>
<select class="form-control" name="selectedBranch" id="selectedBranch"></select>
<div class="invalid-feedback"></div>
</div>
</div>
<div class="col-3">
<label for="purchasePrice" class="col-form-label">Purchase Price</label>
<div class="input-group">
<div class="input-group-prepend"><span class="input-group-text input-group-addon" style="padding: 0.4rem 0.75rem 0.3rem 0.75rem;">₹</span></div>
<input id="purchasePrice" name="purchasePrice" type="text" class="form-control" aria-label="Amount" style="text-align:right;">
</div>
<div class="invalid-feedback"></div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button id="btnSubmit" type="button" class="btn btn-primary">Save</button>
</div>
</div>
By the way I am using jQuery in Spring boot and everything is working fine(save, update, delete) except for validation from jQuery.
Please help!!
I can't see working code because you using some external references like selectize.
I suggest you get used to "snippets" to provide code.
Bytheway, your problem seems to be just about styles. I can't know, but my bet is you just need to provide a css style for
.select::after.error {
color:red;
}
You can inspect and copy CSS code.
The problem is in Your HTML, the nodes of your .input-group does not have allways the same structure. In some cases you have .invalid-feedback just after the input such as this HTML
<div class="form-group">
<label for="serialNo" class="col-form-label"><span class="text-danger">*
</span>Serial No.</label>
<input type="text" class="form-control" id="serialNo" name="serialNo">
<div class="invalid-feedback"></div>
</div>
For other fields the .invalid-feedback isn't after the input but outside from .form-group. take a look
<div class="input-group date" data-date-format="dd-M-yyyy">
<input type="text" class="form-control" id="purchaseDate" name="purchaseDate" />
<span class="input-group-text input-group-append input-group-addon">
<i class="simple-icon-calendar"></i>
</span>
</div>
<div class="invalid-feedback"></div>
This difference in HTML structure of the form made your showFieldError() and clearFieldError() not working allways as you expected, because $(element).next() don't catch the right DOM node for insert/remove the validation message. So in some cases clearFieldError remove the wrong HTML tag and this can make your selects disappear
function showFieldError(element, message) {
$(element).addClass('is-invalid');
$(element).next().html(message);
$(element).next().show();
}
function clearFieldError(element) {
$(element).removeClass('is-invalid');
$(element).removeAttr('required');
$(element).next().html('');
}
So you have to fix Your HTML to obtain the same structure for all fields. Put the <div class="invalid-feedback"></div> allways just below the select or input field. Otherwise you have to change the selector that you pass to showFieldError() and clearFieldError() functions according to your HTML
Otherwise a simply approach is to add a ID to divs with class .invalid-feedback, an ID which you can easily manage by his related input ID, something like
<div class="input-group date" data-date-format="dd-M-yyyy">
<input type="text" class="form-control" id="purchaseDate" name="purchaseDate" />
<span class="input-group-text input-group-append input-group-addon">
<i class="simple-icon-calendar"></i>
</span>
</div>
<div id="purchaseDate_err_mex" class="invalid-feedback"></div>
in this way you can pass the input name to your functions and them becomes
function showFieldError(input_id, message) {
$('#'+input_id).addClass('is-invalid');
$('#'+ input_id +'_err_mex').html(message).show();
}
function clearFieldError(input_id) {
$('#'+input_id).removeClass('is-invalid');
//$('#'+input_id).removeAttr('required');
/* don't need to remove required attribute from mandatory fields */
$('#'+ input_name +'_err_mex').html('').hide();
}
and the validation function
function validateForm() {
var validationStatus = true;
if ($('#selectedCategory').val().length == 0) {
showFieldError('selectedCategory', 'Must not be blank');
if (validationStatus) { $('#selectedCategory').focus() };
validationStatus = false;
}
........
return validationStatus;
}
You only check if the length of all fields is more than 0, so you can validate the entire form within a loop
function validateForm() {
var validationStatus = true;
var form_inputs = $('#manageItemsForm input, #manageItemsForm select')
$.each(form_inputs,function(){
var input_id = $(this).attr('name');
clearFieldError(input_id);
if ($.trim($(this).val()).length == 0 && $(this).is("[required]")) {
showFieldError(input_id, 'Must not be blank');
if (validationStatus) { $('#'+input_id).focus() };
validationStatus = false;
}
});
return validationStatus;
}

My AJAX login form in codeigniter always chooses the else statement, even if the conditions are met. How to solve these?

So I looked all across google and stackoverflow to find solution for this problem, but hadn't seen a specific solution. So here's the problem:
Everytime I submit my login form, whether credentials is correct or incorrect, ajax request always chooses the else statement.
Here's my HTML code and Ajax request.
<div class="modal fade" id="modal-section" tabindex="-1" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<img id="logoonly" src="<?php echo base_url() ?>img/cslogo5.png" />
</div>
<form action="#" id="frm_login" class="form-horizontal" method="POST">
<div class="modal-body">
<div class="form-group">
<div id="error_msg" class="alert alert-danger" class="col-md-12" style="text-align: center; display: none">
Incorrect Student number or Password.
</div>
<label for="numbers" class="col-sm-4 control-label">Student No.</label>
<div class="col-sm-6">
<input name="stud_id" id="stud_id" type="number" class="form-control" placeholder="Enter Student No." required="required" />
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-4 control-label">Password</label>
<div class="col-sm-6">
<input name="password" id="password "type="password" class="form-control" placeholder="Enter Password" data-toggle="password" required="required"/>
</div>
</div>
</div>
<div class="modal-footer" >
<p style="float: left; position: absolute; margin-top: 13px"><font size="1">Copyright 2017 &copy BulSU CS Online Portal.</font>
</p>
<a type="submit" value="Login" ><button type="submit" class="btn btn-primary" id="login_btn">Submit</button></a>
<button type="reset" class="btn btn-default" >Clear</button>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#frm_login').submit(function(event) {
event.preventDefault();
$.ajax({
url: '<?php echo base_url('user/do_login'); ?>',
type: 'POST',
data: {
username: $("#stud_id").val(),
password: $("#password").val(),
},
success:function(data)
{
if(data== 'Yes')
{
alert("Success!");
}
else if(data== 'No')
{
$('.alert').show().fadeIn("400");
}
},
});
});
});
</script>
Here's my controller
public function do_login() {
if(isset($_POST['username']))
{
$students = $this->db->get_where("student", array("stud_id ="=>$_POST['username'],"password ="=>$_POST['password']))->result();
if(empty($students))
{
echo "No";
}
else
{
echo "Yes";
}
}
}
Ajax passes the if statement and always chooses the else condition in my Ajax code.
I tried removing ajax, my code is working, I think my problem is with Ajax's condition. I think I just incorrectly written some code, of I lacking a simple line of code.
Thanks for the help!
In your controller try like this..
1.Use $this->input->post() instead of $_POST[] in codeigniter.
2.Your array inside where condition is wrong.So
Change
array("stud_id ="=>$_POST['username'],"password ="=>$_POST['password']);//remove = when from keys of your array
TO
array("stud_id"=>$this->input->post('username'),"password"=>$this->input->post('password'))
Finally
public function do_login() {
if(isset($this->input->post('username')))
{
$students = $this->db->get_where("student", array("stud_id"=>$this->input->post('username'),"password"=>$this->input->post('password')))->result();
if(count($students)>0)
{
echo "Yes";
}
else
{
echo "No";
}
}
}
Your form is storing the username as 'stud_id':
<input name="stud_id" ...>
But in your controller your trying to get from the post 'username':
if(isset($_POST['username']))
Just change that line to use the same value you used in the form:
if(isset($_POST['stud_id']))

Categories

Resources