How to pass checbox value via AJAX,PHP? - javascript

I have a simple login form with checbox remember me. What i want to achieve is when user checked checbox than create cookies else start session but it still start session even I checked checkbox. Can anyone help ?
This is my html:
<form action="PHP/login.php" method="post" class="loginForm">
<div class="form_vkope">
<input type="text" name="prihlNick" placeholder="Nick" class="prihlNick" />
<img src="Obrazky/ios7-person.png" alt="Ikonka postavy">
</div>
<div class="form_vkope">
<input type="password" name="prihlHeslo" placeholder="Heslo" class="prihlHeslo" />
<img src="Obrazky/locked.png" alt="Ikonka zámok">
</div>
<div class="obal_submitov">
<input type="checkbox" name="zapametat" class="zamapetat" /><label for="zapametat"><span></span>Remember me</label>
<input type="submit" name="prihlasit" value="Login" class="prihlasit" />
</div>
</form>
part of my PHP:
$zapametat = $_POST['zapametat']; //checkbox
if ($dbNick == $Snick AND $dbHeslo == $Sheslo) {
if ($ban != 1) {
if (isset($zapametat)) {
setcookie('id',$dbId,time()+86400, '/');
setcookie('nick',$dbNick,time()+86400, '/');
echo "cookie";
}else{
$_SESSION['id'] = $dbId;
$_SESSION['nick'] = $dbNick;
echo "session";
}
}else{
echo "Tvoj účet bol zablokovaný";
}
}else{
echo "Heslo alebo meno sa nezhoduje";
}
}
And my jQuery:
$('.prihlasit').click(function() {
var prihlNick = $('.prihlNick').val();
var prihlHeslo = $('.prihlHeslo').val();
var prihlasit = $('.loginForm .prihlasit');
var checbox = $('.zapametat'); //checkbox
var data = 'prihlNick='+prihlNick+'&prihlHeslo='+prihlHeslo+'&zapametat='+checbox+'&prihlasit='+prihlasit;
if (prihlNick == '' || prihlHeslo == '') {
$('.loginForm :input').addClass('inputError');
}else{
$('.loginForm :input').removeClass('inputError');
$.ajax({
url: 'PHP/login.php',
type: 'POST',
data: data ,
})
.done(function(data) {
$('.vypis_chyba').html(data);
console.log(data);
})
}
});

I would suggest using this:
jQuery
var checbox = $('.zapametat').prop('checked'); //checkbox (jQuery 1.6+)
PHP
if((isset($zapametat))&&($zapametat==true)){

Related

Problem with required warning message and submit form

I'm implemented the code taken from here to check if radio button is checked and if not, see a warning message.
My code works, but I have a button for submit with ajax (jQuery(function($)) that go ahead also if radio input is not checked.
Some idea to avoid to run function jQuery if function validateForm() is validated?
Here my code:
document.getElementById("filter").onsubmit = validateForm;
function validateForm() {
var validConsumo = validateConsumo();
//if all fields validate go to next page
return validConsumo;
}
function validateConsumo() {
var select = document.getElementById("filter").select,
errorSpan = document.getElementById("error_select"),
isChecked = false,
i;
errorSpan.innerHTML = "";
for (i = 0; i < select.length; i += 1) {
if (select[i].checked) {
isChecked = true;
break;
}
}
if (!isChecked) {
errorSpan.innerHTML = "* You must pick a value";
return false;
}
return true;
}
jQuery(function($) {
$('#filter').submit(function() {
var filter = $('#filter');
$.ajax({
url: filter.attr('action'),
data: filter.serialize(), // form data
type: filter.attr('method'), // POST
beforeSend: function(xhr) {
filter.find('button').text('Filtering...'); // changing the button label
},
success: function(data) {
filter.find('button').text('Filter'); // changing the button label back
$('#response').html(data); // insert data
}
});
return false;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">
<label class="toggler-wrapper style-19">
<input type="radio" name="select" onchange="changeThis1(this)">
<div class="toggler-slider">
<div class="toggler-knob"></div>
</div>
</label>
<div class="my"><strong>1</strong></div>
<label class="toggler-wrapper style-19">
<input type="radio" name="select" onchange="changeThis2(this)">
<div class="toggler-slider">
<div class="toggler-knob"></div>
</div>
</label>
<div class="my"><strong>2</strong></div>
<br>
<span id="error_select" class="error"></span>
<div class="buttonfiltra" id="buttonfiltra">
<button id="link-ida">Filter</button>
<input type="hidden" value="valuefilter" class="submit" id="link-id" name="action">
</div>
</form>
function validateForm() {
var validConsumo = validateConsumo();
//if all fields validate go to next page
return validConsumo;
}
function validateConsumo() {
var select = document.getElementById("filter").select,
errorSpan = document.getElementById("error_select"),
isChecked = false,
i;
errorSpan.innerHTML = "";
for (i = 0; i < select.length; i += 1) {
if (select[i].checked) {
isChecked = true;
break;
}
}
if (!isChecked) {
errorSpan.innerHTML = "* You must pick a value";
return false;
}
return true;
}
console.log(validateConsumo());
$(document).on("submit", "form#filter", function(e) {
e.preventDefault();
// Check for validations.
if (!validateConsumo()) {
console.log("Failed validation");
return;
}
console.log("Successful validation");
// Rest of the code here.
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#" method="POST" id="filter">
<label class="toggler-wrapper style-19">
<input type="radio" name="select" />
<div class="toggler-slider">
<div class="toggler-knob"></div>
</div>
</label>
<div class="my"><strong>1</strong></div>
<label class="toggler-wrapper style-19">
<input type="radio" name="select" />
<div class="toggler-slider">
<div class="toggler-knob"></div>
</div>
</label>
<div class="my"><strong>2</strong></div>
<br />
<span id="error_select" class="error"></span>
<div class="buttonfiltra" id="buttonfiltra">
<button type="submit" id="link-ida">Filter</button>
<input type="hidden" value="valuefilter" class="submit" id="link-id" name="action" />
</div>
</form>
Remove document.getElementById("filter").onsubmit = validateForm;
and then update jQuery code like this:
$("#filter").on("submit", function (e) {
e.preventDefault();
// Check for validations.
if (!validateForm()) {
return;
}
// Rest of the code here.
});

Loading GIF after submitting form in jQuery in Laravel

I want to send an email after submitting a form in Laravel. For complete the send mail process Laravel needs sometimes(5-10 seconds). In that duration (5-10 seconds) I want to show a loader gif. While the mail is send the gif will disappear and a successful message will show.
Here is my form
<div class="book-appointment">
<img src="images/loader.gif" id="gif" style="display: block; margin: 0 auto; width: 100px; visibility: hidden;">
<h2>Make an appointment</h2>
<form action="#" method="post" style="margin-top: 3rem;">
<div class="left-agileits-w3layouts same">
<div class="gaps">
<p>Patient Name</p>
<input type="text" name="Patient Name" placeholder="" required=""/>
</div>
<div class="gaps">
<p>Phone Number</p>
<input type="text" name="Number" placeholder="" required=""/>
</div>
<div class="gaps">
<p>Email</p>
<input type="email" name="email" placeholder="" required="" />
</div>
<div class="gaps">
<p>Age</p>
<input type="text" name="age" placeholder="" required="" />
</div>
</div>
<div class="right-agileinfo same">
<div class="gaps">
<p>Select Date</p>
<input id="datepicker1" name="Text" type="text" value="" onfocus="this.value = '';" onblur="if (this.value == '') {
this.value = 'yy/mm/dd';}" required="">
</div>
<div class="gaps">
<p>Time</p>
<input type="text" id="timepicker" name="Time" class="timepicker form-control" value="">
</div>
<div class="gaps">
<p>Department</p>
<select class="form-control">
<option></option>
<option>Cardiology</option>
<option>Ophthalmology</option>
<option>Neurology</option>
<option>Psychology</option>
<option>Dermatology</option>
</select>
</div>
<div class="gaps">
<p>Gender</p>
<select class="form-control">
<option></option>
<option>Male</option>
<option>Female</option>
</select>
</div>
</div>
<div class="clear"></div>
<input type="submit" value="Make an appointment">
</form>
</div>
My script
$('#add').click(function(event){
$('#gif').css('visibility', 'visible');
var patient_name = $('#patient_name').val();
var patient_number = $('#patient_number').val();
var patient_email = $('#patient_email').val();
var patient_age = $('#patient_age').val();
var patient_gender = $('#patient_gender').find(":selected").val();
var service_id = $('#service_id_search').find(":selected").val();
var schedule_time_id = $('#schedule_time_id').find(":selected").val();
var date = $('#datepicker1').val();
if(patient_name == '' || patient_number == '' || patient_email == '' || patient_age == '' || patient_gender == '' || service_id == '' || schedule_time_id == '' || date == '')
{
alert('Empty input field exist');
}
else if(isNaN(patient_number))
{
alert('Please insert numbers in Patient Number field');
}
else if(isNaN(patient_age))
{
alert('Please insert numbers in Age field');
}
else
{
$.get( 'confirm_appointment', {'patient_name': patient_name, 'patient_number': patient_number, 'patient_email': patient_email, 'patient_age': patient_age, 'patient_gender': patient_gender, 'service_id': service_id, 'schedule_time_id': schedule_time_id, 'date': date, '_token':$('input[name=_token]').val()}, function( data )
{
// console.log(data);
$('#exampleModal .bg-agile .book-appointment h2').remove();
$('#exampleModal .bg-agile .book-appointment form').remove();
trHTML = '';
if(data > 0)
{
trHTML += "<h2> Your appointment is successfully submitted </h2>";
}
else
{
trHTML += "<h2> No </h2>";
}
trHTML += "<center><a href='/'><button class='btn btn-secondary btn-lg' style='padding: 16px 20px 20px 20px; color: #fff; margin-top:20px;'>Go Back to Homepage</button></a></center>";
$('#exampleModal .bg-agile .book-appointment').append(trHTML);
// console.log(data);
// $("#report").load(location.href + " #report");
});
}
});
I have already see this article [Show loading gif after clicking form submit using jQuery but not working...
Anybody help please ?
Showing a div while sending an ajax request, You can use ajaxStop() and ajaxStart() together. here is an example.
var $loading = $('#yourloadingdiv').hide();
$(document)
.ajaxStart(function () {
$loading.show();
})
.ajaxStop(function () {
$loading.hide();
});
Hope this helps.
you could use in this way
//start actions
$('#your-loader').show();
$.post(endpoint, options, function(response){
$('#your-loader').hide();
}).fail(function(){
$('#your-loader').hide();
});
Add id both form and image.
Now inside javascript $('#add').click(function(event){}) function do the following
$('#appointment-form').hide();
$('#gif').show();
While successfully send the mail, just hide the gif id lnside the ajax
$('#gif').hide();
Here is my full code
$('#add').click(function(event){
$('#appointment-form').hide();
$('#gif').css('margin-top','80px');
$('#gif').show();
var patient_name = $('#patient_name').val();
var patient_number = $('#patient_number').val();
var patient_email = $('#patient_email').val();
var patient_age = $('#patient_age').val();
var patient_gender = $('#patient_gender').find(":selected").val();
var service_id = $('#service_id_search').find(":selected").val();
var schedule_time_id = $('#schedule_time_id').find(":selected").val();
var date = $('#datepicker1').val();
if(patient_name == '' || patient_number == '' || patient_email == '' || patient_age == '' || patient_gender == '' || service_id == '' || schedule_time_id == '' || date == '')
{
alert('Empty input field exist');
}
else if(isNaN(patient_number))
{
alert('Please insert numbers in Patient Number field');
}
else if(isNaN(patient_age))
{
alert('Please insert numbers in Age field');
}
else
{
$.get( 'confirm_appointment', {'patient_name': patient_name, 'patient_number': patient_number, 'patient_email': patient_email, 'patient_age': patient_age, 'patient_gender': patient_gender, 'service_id': service_id, 'schedule_time_id': schedule_time_id, 'date': date, '_token':$('input[name=_token]').val()}, function( data )
{
$('#exampleModal .bg-agile .book-appointment h2').remove();
$('#exampleModal .bg-agile .book-appointment form').remove();
trHTML = '';
if(data > 0)
{
trHTML += "<h2 style:'margin-top'> Your appointment is successfully submitted </h2>";
}
else
{
trHTML += "<h2> No </h2>";
}
trHTML += "<center><a href='/'><button class='btn btn-secondary btn-lg' style='padding: 16px 20px 20px 20px; color: #fff; margin-top:20px;'>Go Back to Homepage</button></a></center>";
$('#gif').hide();
$('#exampleModal .bg-agile .book-appointment').append(trHTML);
});
}
});

Can't send data from ajax call to php to get database value

I've a problem to retrieve my data from database.
In my Ajax call, i have tested my form values and it worked.
$(document).ready(function(){
$("form#form").submit(function(event) {
event.preventDefault();
var color = $('#Color').val();
var radio = $('input[name="filter_opties"]:checked').val();
filter(color, radio);
$.ajax({
type: "POST",
url: "db_querys.php",
data: {'color' : color, 'radio' : radio},
success: function(data) {
alert(data);
}
});
});
But in my db_querys.php, I can't get the values of color and radio.
<?php
$gekozenGemeente = $_POST['color'];
$gekozenCategorie = $_POST['radio'];
if($gekozenGemeente != null)
{
echo $gekozenGemeente . $gekozenCategorie;
}
else
{
echo "<br> Values are null";
}
?>
This is my form:
<form id = "form" action="#" method="post" >
<!----- Select Option Fields Starts Here ----->
<label class="heading">Selecteer uw gemeente:</label>
<br>
<select name="Color" id="Color">
<option value="heemstede">Heemstede</option>
<option value="bloemendaal">Bloemendaal</option>
</select>
<br>
<!---- Radio Button Starts Here ----->
<label class="heading">Radio Buttons :</label><br>
<input type="radio" id="radio1" name="filter_opties" value="Betaald"><label for="radio1">Betaald</label><br/>
<input type="radio" id="radio2" name="filter_opties" value="Vergunning"><label for="radio2">Vergunning</label><br/>
<input type="radio" id="radio3" name="filter_opties" value="Blauwe zone"><label for="radio3">Blauwe zone</label><br/>
<br>
<input id= "submit" name="submit" type="submit" value="Get Selected Values" onclick="filter()">
</form>
Can you guys explain what I'm missing?
EDIT: Added the filter function.
function filter(color, radio){
var locations = <?= json_encode($markers_json ); ?>;
var locations2 = JSON.parse(locations);
var polygons = <?=json_encode($polygons_json );?>;
//var polygons2 = JSON.parse(polygons);
//document.getElementById("demo").innerHTML = polygons2;
initialize(locations2,polygons)
}
$(document).ready(function(){
$("#form").submit(function(event) {
event.preventDefault();
var color = $('#Color').val();
var radio = $('input[name="filter_opties"]:checked').val();
filter(color, radio);
$.ajax({
type: "POST",
url: "db_querys.php",
data: {'color' : color, 'radio' : radio},
success: function(data) {
alert(data);
}
});
});

Automatic Login Using JavaScript not Working Properly

I would like it such that a user only has to sign-in once and then the next time they open the hybrid app the get signed in automatically. The JavaScript code below here works but only when I remove the 'login/submit' div () which I need. How can I get around this?
HTML;
<body>
<form name="EventConfirmRedirection" class="Form" method="post" action="index.php" id="myForm" data-ajax="false">
<div class="user_login3"><input style="text-transform:lowercase" type="text" name="username" id="username" placeholder="username"></div>
<div class="user_login3"><input type="password" name="password" id="password" placeholder="password"></div>
<div style="margin-left:5%; width:45%; font-size:5px;">
<input data-theme="c" type="checkbox" id="rememberMe" name="rememberMe"/>
<label for="rememberMe"><span style="font-size:12px">remember me</span></label>
</div>
<div style="margin-left:5%; color:#FF0000; font-weight:bold" id="error"></div>
<div class="login"><input type="submit" value="LOGIN" name="submit" data-theme="e" id="submit"></div>
</form>
</body>
JAVASCRIPT;
$(document).ready(function() {
"use strict";
if (window.localStorage.checkBoxValidation && window.localStorage.checkBoxValidation !== '') {
$('#rememberMe').attr('checked', 'checked');
$('#username').val(window.localStorage.userName);
$('#password').val(window.localStorage.passWord);
document.EventConfirmRedirection.submit();
} else {
$('#rememberMe').removeAttr('checked');
$('#username').val('');
$('#password').val('');
}
$('#rememberMe').click(function() {
if ($('#rememberMe').is(':checked')) {
// save username and password
window.localStorage.userName = $('#username').val();
window.localStorage.passWord = $('#password').val();
window.localStorage.checkBoxValidation = $('#rememberMe').val();
} else {
window.localStorage.userName = '';
window.localStorage.passWord = '';
window.localStorage.checkBoxValidation = '';
}
});
});
AJAX
$(document).ready(function() {
"use strict";
$("#submit").click( function(e) {
e.preventDefault();
if( $("#username").val() === "" || $("#password").val() === "" )
{
$("div#error").html("Both username and password are required");
} else {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(data) {
$("div#error").html(data);
});
$("#myForm").submit( function() {
return false;
});
}
});
});
#chiboz in your javascript, instead of using:
document.EventConfirmRedirection.submit();
use:
$('#submit').click();

JQuery click and submit not firing, while change does

I have a dynamic DOM with add and save button to add a new elements and to save all the data in DOM elements, respectively. Meanwhile each row has its own remove button to remove the corresponding line.
When user log in to the system, she will be redirected to homepage by controller. (I am using codeigniter framework for PHP). This controller will pass all the session and another data to populate user's home page including the DOM data that I mentioned in the previous paragraph.
So I have two different forms in the same page. Here is the first form
<form class="frm_GP" name="frm_GP" id="frm_GP" enctype="multipart/form-data" action="<?php echo base_url();?>index.php/users/save_preference" method="post">
<div class="table" id="preference_GP">
<?php echo $userGP_html ?>
</div>
<div class="tr">
<div class="td">
<input class="button" type="button" name="btn_Add_GP" id="btn_Add_GP" value="Add category" />
</div>
<div class="td">
<input class="button" type="submit" name="btn_Save_GP" id="btn_Save_GP" value="Save" />
</div>
</div>
<input type="hidden" id="formName" name="formName" value="GP" />
<!--<input type="hidden" id="Dropdown_GP" name="Dropdown_GP" value="<?php echo $Dropdown_GP;?>" />-->
</form>
and the second one
<form class="frm_GP" name="frm_GP" id="frm_GP" enctype="multipart/form-data" action="<?php echo base_url();?>index.php/users/save_preference" method="post">
<div class="table" id="preference_GP">
<?php echo $userGP_html ?>
</div>
<div class="tr">
<div class="td">
<input class="button" type="button" name="btn_Add_GP" id="btn_Add_GP" value="Add category" />
</div>
<div class="td">
<input class="button" type="submit" name="btn_Save_GP" id="btn_Save_GP" value="Save" />
</div>
</div>
<input type="hidden" id="formName" name="formName" value="GP" />
<!--<input type="hidden" id="Dropdown_GP" name="Dropdown_GP" value="<?php echo $Dropdown_GP;?>" />-->
</form>
And here is my jQuery codes :
<script type="text/javascript">
jQuery(document).ready(function(){
var fileId = 0;
var wrapperGP = jQuery("#preference_GP");
var wrapperCP = jQuery("#preference_CP");
var logout_button = jQuery("#btn_Logout");
var x = 0;
jQuery('.datepicker').datepicker({
minDate: new Date()
});
jQuery('[name^=frm_]').on('submit', '[name*="btn_Save"]', (function(e){
alert('aa');
var elementID = jQuery(this).closest('[name^=frm_]').attr('id');
var preference = jQuery.fn.getPreference(elementID);
var len = jQuery('.selCat'+preference).length;
var selCat = jQuery('.selCat'+preference);
var selSubCat = jQuery('.selSubCat'+preference);
var score = jQuery('.score');
var valid_score = ["10","20","30","40","50","60","70","80","90","100"];
for(i=0;i<len;i++){
var j = eval(i+1);
alert(jQuery(score).eq(i));
if(jQuery(selCat).eq(i).val()==='0'){
jQuery(selCat).get(i).focus();
jQuery('[name=error'+preference+']').html('Please select the category of row '+ j);
return false;
}
if(jQuery(selSubCat).eq(i).val()==='0'){
jQuery(selSubCat).get(i).focus();
jQuery('[name=error'+preference+']').html('Please select the sub category of row '+ j)
return false;
}
if(jQuery(score).eq(i).val()==='0' || jQuery(score).eq(i).val()==0 || jQuery(score).eq(i).val()===''){
jQuery(score).get(i).focus();
jQuery('[name=error'+preference+']').html('Please fill the score of row '+ j)
return false;
}
if(valid_score.indexOf(jQuery(score).eq(i).val())<0){
//jQuery(score).get(i).focus();
jQuery('[name=error'+preference+']').html('Please fill with the valid score at row '+ j)
return false;
}
}
//jQuery( "#frm"+preference ).submit();
return false;
}));
jQuery.fn.getPreference = function(elementID) {
var index = elementID.lastIndexOf('_');
var preference = elementID.substr(index,elementID.length);
return preference;
}
jQuery('[name^=frm_]').on('click', '[name*="btn_Add"]', (function(e){
alert('this');
/*
var elementID = jQuery(this).attr('id');
var preference = jQuery.fn.getPreference(elementID);
alert('this');
var dropdown = jQuery(".Dropdown"+preference).val();
e.preventDefault();
x++;
if(preference==="_GP"){
jQuery('#preference'+preference).append(dropdown);
}else{
jQuery('#preference'+preference).append(dropdown);
}
*/
/*
$.post('<?php echo base_url();?>'+'index.php/client/ajax_cat',{preference:preference}, function(returned){
jQuery('#preference'+preference).append(returned);
jQuery("[name*='selCat']").change(function(){
var elementID = jQuery(this).attr('class');
var preference = jQuery.fn.getPreference(elementID);
var index = jQuery(this).index('.selCat'+preference);
var value = jQuery(this).val();
var selSubCat = (".selSubCat"+preference);
jQuery('[name=error'+preference+']').html('');
$.post('<?php echo base_url();?>'+'index.php/client/ajax_subcat',{id:value}, function(returned){
jQuery(selSubCat+":eq("+index+")").html(returned);
});
});
});
*/
return false;
}));
jQuery("[name*='selCat']").change(function(){
var elementID = jQuery(this).attr('class');
var preference = jQuery.fn.getPreference(elementID);
var index = jQuery(this).index('.selCat'+preference);
var value = jQuery(this).val();
var selSubCat = (".selSubCat"+preference);
jQuery('[name=error'+preference+']').html('');
$.post('<?php echo base_url();?>'+'index.php/client/ajax_subcat',{id:value}, function(returned){
jQuery(selSubCat+":eq("+index+")").html(returned);
});
return false;
});
jQuery(wrapperGP).on("click","#btnRemove", function(e){
e.preventDefault();
jQuery(this).closest(".tr").remove();
x--;
return false;
});
jQuery(wrapperCP).on("click","#btnRemove", function(e){
e.preventDefault();
jQuery(this).closest(".tr").remove();
x--;
return false;
});
});
</script>
Any idea why the submit, click and change functions are not firing? meanwhile the remove is working ?
After few tries, changing the naming in jquery it finally works now.
I change from this
jQuery('[name^=frm_]').on('submit', '[name*="btn_Save"]', (function(e){
//code here
});
to
jQuery('[name*=frm_]').on('click', '[name*=btn_Save]', (function(e){
//code here
});
name^=frm_ is not working. it's supposed to find all the elements that have name begin with frm_. Replaced the ^ with * which is to find the elements that contain frm_ as a name.
And also, I guess there is no submit as a parameter in jQuery's event listener even though the type of the input is a submit not a button.
and I did the same thing for the "btn_Add" on click

Categories