Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checkbox - checked or unchecked with jQuery and MySQL

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?

like image 247
Dennis Lauritzen Avatar asked May 16 '11 12:05

Dennis Lauritzen


3 Answers

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');
        }
    });
});
like image 91
fearofawhackplanet Avatar answered Oct 23 '22 04:10

fearofawhackplanet


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
                }
});
like image 17
Sarah West Avatar answered Oct 23 '22 02:10

Sarah West


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

    }
}
like image 2
glutorange Avatar answered Oct 23 '22 03:10

glutorange