Ajax call on checking a checkbox - javascript

I am having a two checkboxes.Now on click of one of the checkbox I want to make an ajax call to a jsp page.That jsp page is to show a table that contains datat being fetched from database.
Now,The problem is say i have two checkboxes like :
<div class="search-inputs">
<input class="searchName" type="text" placeholder="Search Here.."></input>
<input class="searchType1" type="checkbox" name="emailNotification"><label class="searchtype1label">Email Notification</label></input>
<input class="searchType2" type="checkbox" name="SharingNotification"><label class="searchtype2label">File Sharing Notification</label></input>
<input class="searchDateFrom" type="text" placeholder="Search From"></input>
<input class="searchDateTo" type="text" placeholder="Search To"></input>
<input class="Datesubmit" type="button" value="Search"></input>
<div id="container"></div>
How to do it ?Please help
My Script part :
$(document).ready(function () {
$('.search-select').on('change', function(){
$('.search-inputs').children().hide();
var classn =$(this).find(":selected").val();
//alert(classn);
if(classn=='searchName')
{
//alert("searchname");
$('.'+"searchName").show();
}
else if(classn=='searchType')
{
//alert("searchType");
$('.'+"searchType1").show();
$('.'+"searchtype1label").show();
$('.'+"searchType2").show();
$('.'+"searchtype2label").show();
}
else if(classn=='searchDate'){
//alert("searchType");
$('.'+"searchDateFrom").show();
$('.'+"searchDateTo").show();
$('.'+"Datesubmit").show();
}
});
$('#emailNotification').on('change',function() {
//var checked = $(this).is(':checked');
if(this.checked){
//alert("in");
$.ajax({
type: "POST",
url: "searchOnType.jsp",
data: {mydata: "emailNotification"},
success: function(data) {
alert('it worked');
$('#container').html(data);
},
error: function() {
alert('it broke');
},
complete: function() {
alert('it completed');
}
});
}
});
});
But how to show the table on the same page ?

you have to change your html slightly with this--
give same class name to both check boxes.
<input class="searchType" type="checkbox" name="emailNotification" id="emailNotification"><label class="searchtype1label">Email Notification</label></input>
<input class="searchType" type="checkbox" name="SharingNotification" id="SharingNotification"><label class="searchtype2label">File Sharing Notification</label></input>
Now slightly change in jquery part--
$('.searchType').click(function() {
alert($(this).attr('id')); //-->this will alert id of checked checkbox.
if(this.checked){
$.ajax({
type: "POST",
url: 'searchOnType.jsp',
data: $(this).attr('id'), //--> send id of checked checkbox on other page
success: function(data) {
alert('it worked');
alert(data);
$('#container').html(data);
},
error: function() {
alert('it broke');
},
complete: function() {
alert('it completed');
}
});
}
});

you have to use change event for this like below:
Html:
<input class="searchType1" type="checkbox" name="emailNotification"><label class="searchtype1label">Email Notification</label></input>
<input class="searchType2" type="checkbox" name="SharingNotification"><label class="searchtype2label">File Sharing Notification</label></input>
<div id="container">
</div>
JQuery:
$('#emailNotification').on('change',function() {
if(this.checked){
$.ajax({
type: "POST",
url: "searchOnType.jsp",
data: {mydata:"emailNotification"},
success: function(data) {
alert('it worked');
$('#container').html(data);
},
error: function() {
alert('it broke');
},
complete: function() {
alert('it completed');
}
});
}
});

Related

Remove the required attribute after the sucees of form submission

I have a form on click of submit the input box is highlighted with the red color border if it is empty. Now i have jquery ajax form submission on success of the form i will display a message "data submitted" and i will reset the form so all the input fields will be highlighted in red color. Now i want to empty the fields after the success of form submission and it should not be highlighted in red color.
HTML
(function() {
'use strict';
window.addEventListener('load', function() {
var form = document.getElementById('index-validation');
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
}, false);
})();
$(".index-form").submit(function(e) {
e.preventDefault();
return false;
}
else {
var ins_date = new Date($.now()).toLocaleString();
var parms = {
name: $("#name").val(),
email: $("#email").val(),
inserted_date: ins_date
};
var url2 = "http://localhost:3000/api";
$.ajax({
method: 'POST',
url: url2 + "/homes",
async: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(parms),
success: function(data) {
console.log('Submission was successful.');
$(".alert-success").removeClass("d-none");
$(".alert-success").fadeTo(2000, 500).slideUp(500, function() {
$(".alert-success").slideUp(500);
});
$('.index-form')[0].reset();
console.log(data);
},
error: function(data) {
console.log('An error occurred.');
console.log(data);
},
})
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="container index-form" id="index-validation" novalidate>
<input class="form-control" type="text" id="name" name="name" placeholder="Your name" required>
<input class="form-control" type="email" id="email" name="email" placeholder="Email Address" required>
<div class="invalid-feedback">Please Enter a Valid Email Id.</div>
<input type="submit" id="submit" class="btn btn-default btn-lg btn-block text-center" value="Send">
</form>
I'm not clear with your question, Do you want to reset form or remove the error class. But anyways I'll try solving out both :
SCRIPT
<script type="text/javascript">
(function() {
'use strict';
window.addEventListener('load', function() {
var form = document.getElementById('index-validation');
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
}, false);
})();
$(".index-form").submit(function(e) {
e.preventDefault();
return false;
} else {
var ins_date=new Date($.now()).toLocaleString();
var parms = {
name : $("#name").val(),
email : $("#email").val(),
inserted_date:ins_date
};
var url2="http://localhost:3000/api";
$.ajax({
method: 'POST',
url: url2 + "/homes",
async: false,
dataType : "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(parms),
success: function(data){
console.log('Submission was successful.');
//if you are removing specific property from class
$(".alert-success").css('display', 'none');
$(".alert-success").fadeTo(2000, 500).slideUp(500, function(){
$(".alert-success").slideUp(500);
});
$("form")[0].reset();
console.log(data);
}, error: function (data) {
console.log('An error occurred.');
console.log(data);
},
})
}
});
</script>
Jquery doesn't support any method such as reset() of javascript, So you can trigger javascript's reset() method.
Feel free to ask doubts if stuck. Happy coding....!!!!!
$(this.('.index-form').find("input[type=text]").val("");
You can just empty the form value by giving the .val() as empty, you have to give this on after your ajax response.
and also instead of using fade in and fade out just try to use hide and show function both may work like same.

Displaying delete icon when checkbox is selected - JS

I am trying to do this, when a user checks at least one box, the icon must show if not, it hides.
With my code, when i select the #mastercheckbox, the icon does show but when i select the other checkbox displaying on each row, it doesn't show.
Why is this happening?
HTML:
<table id="users-table" class="table table-hover table-condensed" style="width:100%">
<thead>
<tr>
<th><input type="checkbox" id="master"></th>
<th>Category</th>
<th>Description</th>
<th>Number of Items</th>
<th>Action</th>
</tr>
</thead>
</table>
<script type="text/javascript">
$(document).ready(function() {
oTable = $('#users-table').DataTable({
"processing": true,
"serverSide": true,
"bProcessing":false,
"bSort":false,
"ajax": "{{ route('datatable.getcategories') }}",
"columns": [
{data: 'checkbox', name: 'checkbox', orderable: false, searchable: false},
{data: 'name', name: 'name'},
{data: 'action', name: 'action', orderable: false, searchable: false}
],
});
});
</script>
Controller:
$stduents= Student::all();
return Datatables::of($student)->addColumn('checkbox', function ($std) {
return '<input type="checkbox" class="sub_chk" data-id="'.$std->id.'">';
})->make(true);
Where i select my checkbox:
<script type="text/javascript">
$(document).ready(function () {
$("i[type='icon']").css('display','none'); //set style explicitly
$('#master').on('click', function(e) {
if($(this).is(':checked',true))
{
$(".sub_chk").prop('checked', true);
} else {
$(".sub_chk").prop('checked',false);
}
});
$('.delete_all').on('click', function(e) {
var allVals = [];
$(".sub_chk:checked").each(function() {
allVals.push($(this).attr('data-id'));
});
if(allVals.length <=0)
{
alert("Please select row.");
}
else {
var check = confirm("Are you sure you want to delete this row?");
if(check == true){
var join_selected_values = allVals.join(",");
$.ajax({
url: $(this).data('url'),
type: 'GET',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: 'ids='+join_selected_values,
success: function (data) {
if (data['success'])
{
$("#" + data['tr']).slideUp("slow");
location.reload();
alert(data['success']);
}
else if (data['error'])
{
alert(data['error']);
}
else
{
//alert('Whoops Something went wrong!!');
}
},
error: function (data) {
alert(data.responseText);
}
});
$.each(allVals, function( index, value )
{
$('table tr').filter("[data-row-id='" + value + "']").remove();
});
}
}
});
$('[data-toggle=confirmation]').confirmation({
rootSelector: '[data-toggle=confirmation]',
onConfirm: function (event, element) {
element.trigger('confirm');
}
});
$(document).on('confirm', function (e) {
var ele = e.target;
e.preventDefault();
$.ajax({
url: ele.href,
type: 'GET',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
success: function (data) {
if (data['success'])
{
$("#" + data['tr']).slideUp("slow");
location.reload();
alert(data['success']);
}
else if (data['error']) {
alert(data['error']);
}
else
{
alert('Whoops Something went wrong!!');
}
},
error: function (data) {
alert(data.responseText);
}
});
return false;
});
});
</script>
Display icon when at least one checkbox is selected:
<script>
$("input[type='checkbox']").click(function() {
var atLeastOneChecked = false;
$("input[type='checkbox']").each(function(index) {
if ($(this).prop('checked'))
atLeastOneChecked = true;
});
if (atLeastOneChecked) {
$("i[type='icon']").show(); //built-in jquery function
//...or...
$("i[type='icon']").css('display','inline-block'); //or set style explicitly
} else {
$("i[type='icon']").hide(); //built-in jquery function
//...or...
$("i[type='icon']").css('display','none'); //set style explicitly
}
});
</script>
Since your checkboxes are added after the page load $("input[type='checkbox']").click(...) will not add the event handler to them. i.e.
//will handle clicked events on checkbox existing when this js runs
$('input[type="checkbox"]').click(function() {
alert('clicked')
});
//will handle clicked events on dynamically added checkboxes
$(document).on('click', 'input[type="checkbox"]', function() {
alert('clicked2');
});
//add new checkbox to page
$('button').click(function() { $('#master').after($('<input type="checkbox" >')) });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" id="master">
<button type='button'>Add Checkbox</button>
What you want to do instead is $(document).on('click', 'input[type="checkbox"]', function() { ... }
A simple example works for me - whatever is going wrong for you, you'll have to either provide more code or narrow in on the problem with some debugging of your own.
Hope this helps: master and grouped checkboxes all react to click
HTML:
<div id="icon">SEE ME?</div>
<div id="info">Information</div>
<div><input type="checkbox" id="master"></div>
<div><input type="checkbox" name="subset01[]" value="00"></div>
<div><input type="checkbox" name="subset01[]" value="01"></div>
<div><input type="checkbox" name="subset01[]" value="02"></div>
<div><input type="checkbox" name="subset01[]" value="03"></div>
<div><input type="checkbox" name="subset01[]" value="04"></div>
<div><input type="checkbox" name="subset01[]" value="05"></div>
<div><input type="checkbox" name="subset01[]" value="06"></div>
<div><input type="checkbox" name="subset01[]" value="07"></div>
<div><input type="checkbox" name="subset01[]" value="08"></div>
<div><input type="checkbox" name="subset01[]" value="09"></div>
CSS:
#icon{ display: none; }
JS:
$( function(){
$('#info').text("please click a checkbox");
$( "input[type='checkbox']" ).click( function(){
$('#info').html( "you clicked # "+ new Date().getTime() +" currently "+ $(':checked').length +" checked" );
if( $(':checked').length ){
$("#icon").show();
}else{
$("#icon").hide();
}
} );
} );

Require radio button html and javascript

I have the following html code
<input type="radio" name="months" value="TBI-6">
<input type="radio" name="months" value="UNI-6">
And i have this submitt button
$('#button-confirm').on('click', function() {
$.ajax({
type: 'post',
url: 'index.php?route=payment/zero_rate/confirm',
cache: false,
data:{
egn: $('#input-payment-egn').val(),
months: $('input[name=months]:checked').parent().text() + $('input[name=months]:checked').val()
},
beforeSend: function() {
$('#button-confirm').button('loading');
},
complete: function() {
$('#button-confirm').button('reset');
},
success: function() {
location = '<?php echo $continue; ?>';
}
});
});
How can i validate this two radio buttons? I dont want to let the user to submitt the form and leave the page without choosing one of the radio buttons?
$('input[name=months]:checked').length
should tell you how many radio buttons in the group are checked.
So verify that is above 0 before you continue with the form submission.
Check the radio button if checked
<input type="radio" name="months" value="TBI-6" class="radiobtn">
<button id="button-confirm">
Submit
</button>
$('#button-confirm').on('click', function() {
if($('.radiobtn').is(':checked')) { alert("it's checked");
$.ajax({
type: 'post',
url: 'index.php?route=payment/zero_rate/confirm',
cache: false,
data:{
egn: $('#input-payment-egn').val(),
months: $('input[name=months]:checked').parent().text() + $('input[name=months]:checked').val()
},
beforeSend: function() {
$('#button-confirm').button('loading');
},
complete: function() {
$('#button-confirm').button('reset');
},
success: function() {
location = '<?php echo $continue; ?>';
}
});
} else {
alert("it's not checked");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="months" value="TBI-6" class="radiobtn">
<button id="button-confirm">
Submit
</button>

Send multiple checkbox data with ajax

I have a form where I have countries list in checkbox format to be inserted into database. Say for example:
<input type="checkbox" name="country[]" value="Afghanistan" checked>Afghanistan<br>
<input type="checkbox" name="country[]" value="Albania" checked>Albania<br>
<input type="checkbox" name="country[]" value="Algeria" checked>Algeria<br>
<input type="checkbox" name="country[]" value="American Samoa" checked>American Samoa<br>
<input type="checkbox" name="country[]" value="Andorra" checked>Andorra<br>
<input type="checkbox" name="country[]" value="Angola" checked>Angola<br>
<input type="checkbox" name="country[]" value="Anguilla" checked>Anguilla<br>
I want to insert this into database using ajax. I could have easily done this through normal same page PHP post. But when sending data with ajax to other page for processing I am confused on how to send. Once it sends all the selected checkbox values perfectly then all the rest is onto me.
My AJAX script
$("#submit").click(function() {
var dataString = {
clicks: $("#clicks option:selected").data("value"),
country: $("input[name=country").data("value") // tried using this and input[name=country[]] but they did not work.
};
$.confirm({
title: 'Confirm!',
content: 'Are you sure you want to purchase this advertisement?',
buttons: {
confirm: function () {
$.ajax({
type: "POST",
dataType : "json",
url: "add-ptc-process.php",
data: dataString,
cache: true,
beforeSend: function(){
$("#submit").hide();
$("#loading-rent").show();
$(".message").hide();
},
success: function(json){
setTimeout(function(){
$(".message").html(json.status).fadeIn();
$('#mywallet').html('$' + json.deduct);
$("#loading-rent").hide();
$("#submit").show();
},1000);
}
});
},
cancel: function () {
$.alert('<span style="font-size: 23px">Purchase Cancelled!</span>');
}
}
});
return false;
});
});
I have put a check on the processing page where if the country value is empty return error like:
if($country == ''){
echo "No countries selected. Please select at least one country.";
}
No matter if I select one or all countries still I get this error response back. What should I do to send these checkbox data with ajax?
Try
var countries = {};
$('input[name^="country"]').each(function(){
countries[$(this).attr('value')] = $(this).is(":checked");
});
then post it to ajax data: countries or change the code to send only checked elements
Your PHP will receive an array so you can check
if(is_array($_POST['countries'])){
foreach($_POST['countries'] AS $country_name => $is_checked){
//do something...
}
}
You will want to switch your .data() to .val() on your input capture. Also change the name of the inputs to input[name=country\\[\\]]:checked.
# Use "e" as the event
$("#submit").click(function(e) {
# Use this function to stop the form
e.preventDefault();
# You could make a quick function to save all the countries
# You can actually feed other selectors into this as well, so
# it can do all your value retrievals, not just for countries
function getCountries(checkboxes)
{
var getVals = [];
$.each($(checkboxes),function(k,v) {
getVals.push($(v).val());
});
return getVals;
}
var dataString = {
clicks: $("#clicks option:selected").val(),
# Run the function to gather
# Note the name (escaped [] with :checked)
country: getCountries("input[name=country\\[\\]]:checked")
};
$.confirm({
title: 'Confirm!',
content: 'Are you sure you want to purchase this advertisement?',
buttons: {
confirm: function () {
$.ajax({
type: "POST",
dataType: "json",
url: "add-ptc-process.php",
data: dataString,
cache: true,
beforeSend: function(){
$("#submit").hide();
$("#loading-rent").show();
$(".message").hide();
},
success: function(json){
setTimeout(function(){
$(".message").html(json.status).fadeIn();
$('#mywallet').html('$' + json.deduct);
$("#loading-rent").hide();
$("#submit").show();
},1000);
}
});
},
cancel: function () {
$.alert('<span style="font-size: 23px">Purchase Cancelled!</span>');
}
}
});
});

Form doesn't submit form data populated via AJAX

I'm having the following problem with my code below: when 'productSearchResult' is populated via AJAX, the contents are not included when the form is submitted using the 'Add' button.
UPDATE 1:
Strangely it is working, but only the first time productSearchQuery is populated. Any subsequent populations of productSearchQuery run into the problem above.
HTML:
<form name="productSearch">
<input name="productSearchQuery" type="textbox">
</form>
<form name="productAdd">
<div id="productSearchResult"></div>
</form>
<a>Add</a>
<div id="addResult"></div>
HTML loaded via AJAX into productSearchResult:
<input type="radio" name="productId" value="3944">
<input type="radio" name="productId" value="3946">
<input type="radio" name="productId" value="3999">
JS:
<script type="text/javascript">
function postData(type, url, data, targetDiv) {
$.ajax({
type: type,
url: url,
data: data,
success: function(response) {
$(targetDiv).html(response);
},
error: function() {
alert('Error! Plese try again.');
}
});
return false;
};
$(document).ready(function() {
$('input[name=productSearchQuery]').keyup(function() {
// submit the form
postData('POST', 'search.php', $('form[name=productSearch]').serialize(), '#productSearchResult');
});
$('a').click(function() {
postData('POST', 'add.php', $('form[name=productAdd]').serialize(), '#addResult');
});
});
</script>
UPDATE 2:
OK, first off I want to apologise for not including this code in my original post, I honestly didn't suspect it could be the cause. I've fixed my code after rolling back the JS which is returned with the radio buttons. I can't understand why the new JS causes the problem above, whereas the old JS does not.
Here's the old JS that works fine:
$('tr.product input[type=radio]').hide();
$('tr.product').mouseover(function() {
$(this).addClass('blueHover');
}).mouseout(function() {
$(this).removeClass('blueHover');
});
$('tr.product').click(function(event) {
$('tr.product').removeClass('blueChecked');
$(this).closest('tr').addClass('blueChecked');
if (event.target.type !== 'radio') {
$(':radio', this).attr('checked', true);
}
});
Here's the new JS that causes the problems above:
$('tr.product input[type=radio]').hide();
$(document).on({
mouseenter: function () {
$('td', $(this).parent()).addClass('blueHover');
},
mouseleave: function () {
$('td', $(this).parent()).removeClass('blueHover');
},
click: function (event) {
$('tr.product').removeClass('blueChecked');
$(this).closest('tr').addClass('blueChecked');
if (event.target.type !== 'radio') {
$(':radio', $(this).parent().parent()).attr('checked', false);
$(':radio', $(this).parent()).attr('checked', true);
}
}
}, 'tr.product td');
Try this instead
<script type="text/javascript">
function postData(type, url, data, targetDiv) {
$.ajax({
type: type,
url: url,
contentType: 'application/json',
data: data,
success: function(response) {
$(targetDiv).html(response);
},
error: function() {
alert('Error! Plese try again.');
}
});
return false;
};
$(document).ready(function() {
$('input[name=productSearchQuery]').keyup(function() {
// submit the form
postData('POST', 'search.php', $('form[name=productSearch]').serialize(), '#productSearchResult');
});
$('a').click(function() {
postData('POST', 'add.php', $('form[name=productAdd]').serialize(), '#addResult');
});
});
</script>
You have to use jQuery on method.
$('body').on('click', 'a', function() {
postData('POST', 'add.php', $('form[name=productAdd]').serialize(), '#addResult');
});

Categories

Resources