checkbox - checked or unchecked with jQuery and MySQL - javascript

I am currently creating a system where it has to be possible to check/uncheck a checkbox. Everytime it changes status I need jQuery to make an AJAX call to a page, that updates the database.
How can I do this?

For example you can do it like this:
First you have to look if the checkbox is checked:
$("#yourSelector").live("click", function(){
var id = parseInt($(this).val(), 10);
if($(this).is(":checked")) {
// checkbox is checked -> do something
} else {
// checkbox is not checked -> do something different
}
});
You can load specific content via Ajax:
$.ajax({
type: "POST",
dataType: "xml",
url: "path/to/file.php",
data: "function=loadContent&id=" + id,
success: function(xml) {
// success function is called when data came back
// for example: get your content and display it on your site
}
});

Which bit are you stuck on? You should probably have something like this...
$('#myCheckbox').click(function() {
var checked = $(this).is(':checked');
$.ajax({
type: "POST",
url: myUrl,
data: { checked : checked },
success: function(data) {
alert('it worked');
},
error: function() {
alert('it broke');
},
complete: function() {
alert('it completed');
}
});
});

Detect if checkbox is checked:
if ( $('#id').is(':checked') ) { }
This can be executed in a function that is triggered by "onchange" event.
function checkCheckboxState() {
if ( $('#id').is(':checked') ) {
// execute AJAX request here
}
}

Something like this probably?
$('.checkbox').click(function (){
var val = $(this).is(':checked');
$.load('url_here',{status:val});
});

<input type="checkbox" name="foo" value="bar" class="checkIt"/>
<script type="text/javascript">
$('.checkIt').bind('click', function() {
if($(this).is(":checked")) {
// checkbox is checked
} else {
// checkbox is not checked
}
});
</script>
You can now have more than one checkbox.

Related

Multiple checkbox selection at AJAX when button clicked

<script>
function display() {
$.ajax({
url: "tmp.php",
type: "get",
data: {
a: $('#selecttmp option:selected').val()
}
}).done(function(data) {
$('#result').text(data);
alert(data);
$(document).ready(function() {
$('.#buttontmp').click(function() {
$('.data').prop('checked', this.checked);
});
});
});
}
</script>
When button is clicked, it reads the select option value and check up every relevant checkbox based on their name.
Using AJAX, select option value could be found without any refresh but checkboxes aren't checked. Am I using jquery wrongly?
<script>
function display() {
$.ajax({
url: "test.php",
type: "get",
data: {
a: $('#selectest option:selected').val()
}
}).done(function(data) {
$('#result').text(data);
alert(data);
$('input:checkbox[name='+data+']').each(function() {
this.checked = true;
});
});
}
</script>
I have figure out the solution myself, thanks for the correction that made by #CBroe.

jQuery ajax input field event, options list and setting a value

I am trying to create an AJAX function to autocomplete the input field.
The user starts typing in location/city name, and it should trigger an AJAX call for lookup, presenting suggestions of matching city names list to the input field. Then the user selects one value and that is set to that input field. The below code doesn't even trigger events, I do not see request activity on the network. How to accomplish this?
$(function() {
$('#locationName').keyup(function() { //tried keyup, input
alert('Ok'); // to test event
$.ajax({
type: 'POST',
url: '/locationsearch',
data: {
'search_text': $('#locationName').val()
},
success: searchSuccess,
dataType: 'text'
});
});
});
function searchSuccess(data) {
locationName.val = 'data';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="locationName" id="locationName">
Your example does not seem complete. It's not clear where locationName is defined. Consider the following snippet.
$(function() {
function searchLoc(txt) {
var result = "";
$.post("/locationsarch", {
"search_text": txt
}, function(data) {
result = data;
});
return result;
}
$('#locationName').keyup(function() {
var q = $(this).val();
if (q.length >= 3) {
$(this).val(searchLoc(q));
}
});
});
It's not clear what the resulting data will be, I am assuming text or HTML.

how to make checkbox checked work

In my project, $('#cenDiv').html(data) can work successfully in ajax. Then I want to click the checkbox of selAllAttId, and do something;
If I use onclick="selAllAtt()", and selAllAtt() method can be called successfully, but $(this).attr("checked") became to be true always after finishing the selAllAtt() method, so $(this).attr("checked") is always false and alert("checked") always can not work.
So I want to change another way with $('#selAllAttId').on("change",function(){}) But unlucky, alert("test) can no work. Who can help me?
Here is js code:
<script>
$(document).ready(function()
{
$('#selAllAttId').on("change",function(){
alert("test");//can not work
});
});
function corpAnn()
{
$.ajax({
dataType:'html',
type:"POST",
url:"oat.php",
data: {oaAnn:oaAnn},
success:function(data)
{
$('#cenDiv').html(data);
}
});
}
function selAllAtt(){
alert("checkbox");
var xzyId=document.getElementById('xzyId');//fetch other table id
var checked=xzyId.getElementsByTagName('input');//fetch all table checkbox successfully
if($(this).attr("checked"))//always false.
{
alert("checked");
for(i=0;i<checked.length;i++)
{
checked[i].checked=true;
}
}
else
{
alert("delete");
for(i=0;i<checked.length;i++)
{
checked[i].checked=false;
}
}
});
</script>
<div id="cenDiv"></div>
The code of oat.php is:
echo '<td style="color:Maroon" bgcolor="#888888">
<input type="checkbox" id="selAllAttId" onclick="selAllAtt()">
<b>Num</b>
</td>';
You can use the native HTML node like this:
var checkbox = document.getElementById('selAllAttId');
if(checkbox.checked)
{
// do something
}else{
// do something else
}

preventDefault is not working

I am trying to send an ajax request to complete a task when a link is clicked. For some reason the e.preventDefault is not working and I still get sent to the page. Is there something I am missing?
It is simply supposed to go to the page set the check-box to checked (or unchecked) then redirect. But again it just goes to the page. Any help would be great!
here is the main.js
$(function() {
$('.ajax-task-complete').on({
click: function(e) {
e.stopPropagation();
e.preventDefault();
var href = $(this).attr('href');
$('<div></div>').load(href+' form', function() {
// Set Form
var form = $(this).children('form');
// Set Checkbox
var cb = form.find('input[type="checkbox"]');
// Taggle Checkbox
cb.prop('checked', !cb.prop('checked'));
// Form Action URL
var url = form.attr('action');
// Set Data
var data = form.serialize();
$.ajax({
url: url,
data: data,
method: 'post',
dataType: 'json',
cache: false,
success: function(obj) {
var tic = $('#task-complete-' + obj.id + ' .ajax-task-complete');
},
complete: function() {
console.log('complete');
},
error: function(err) {
console.log(err);
}
});
});
}
});
});
here is the requested button
<td id="task-complete-{{ entity.id }}">
{% if entity.completed %}
<a class="check ajax-task-complete" href="{{ path('task_edit_complete', { 'id': entity.id }) }}">✔</a>
{% else %}
<a class="uncheck ajax-task-complete" href="{{ path('task_edit_complete', { 'id': entity.id }) }}">✔</a>
{% endif %}
</td>
This is your problem:
Uncaught ReferenceError: $ is not defined?
Read HERE from SO how you load your jQuery-plugin the right way.
you might need to stop bubbling depending on where the click event is occurring. Try adding this and see what happens.
e.stopPropagation();
**"$"**
is missing before (function() {
javascript pageload event should be like
$(function(){
//code here
});
or
function will be called by themself
(function(){
//code here
)}();
or
(function($){
//code here
})(jQuery)
You can check the fiddle here
Your scope is wrong, you are missing the () after (function)(). The function is never called :
(function() {
$('.ajax-task-complete').on({
click: function(e) {
e.stopPropagation();
e.preventDefault();
var href = $(this).attr('href');
$('<div></div>').load(href+' form', function() {
// Set Form
var form = $(this).children('form');
// Set Checkbox
var cb = form.find('input[type="checkbox"]');
// Taggle Checkbox
cb.prop('checked', !cb.prop('checked'));
// Form Action URL
var url = form.attr('action');
// Set Data
var data = form.serialize();
$.ajax({
url: url,
data: data,
method: 'post',
dataType: 'json',
cache: false,
success: function(obj) {
var tic = $('#task-complete-' + obj.id + ' .ajax-task-complete');
},
complete: function() {
console.log('complete');
},
error: function(err) {
console.log(err);
}
});
});
}
});
})(); //Add () here
But is the scope really needed here?
Maybe you meant a ready handler, then it should be like this :
$(function); //Missing '$'
Try placing the preventDefault event at the end of the function as below
$('.ajax-task-complete').on({
click: function(e) {
//
//your code here then,
e.preventDefault();
e.stopPropragation();
});
I can't test if it works or not, as I'm on mobile.

Checking whether checkbox has been unchecked

I am trying to send post requests to the database dependant on whether a checkbox is checked or unchecked I want to add to database or delete from database with the post requests. I have managed to successfully get the add working via post request but I am unable to get it to delete using the jQuery below:
$(function () {
$("input:checkbox").change(function () {
var fullURL = document.URL;
var url = fullURL.split('userID=');
var userID = url[1];
var courseID = this.value;
var postData = { 'userId': userID, 'courseID': courseID };
if (!this.checked) {
$.post('/Admin/UnenrolUser/', postData, function (data) {
});
}
if (this.checked) {
$.post('/Admin/EnrolUser/', postData, function (data) {
});
}
});
});
My this.checked if statement seems to be working as expected. How can I get the unchecked to work in this context?
if (this.checked) {
$.post('/Admin/EnrolUser/', postData, function (data) {
});
} else {
$.post('/Admin/UnenrolUser/', postData, function (data) {
});
}
Try this
if(!$(this).is(':checked'))

Categories

Resources