动态显示复选框

I am creating a subscribe/unsubscribe checkbox, on sign up user will be subscribed by default. if user uncheck(unsubscribe) checkbox, it will ask for confirmation in confirm() jquery function and if it return true, ajax request will update value in database, and toggle the checkbox to run subscribe function on next click (without page reload).

MY TRY

PHP

<?php if($newsletter_value){ ?>
        <input id="checkbox" type="checkbox" name="checkbox" value="<?php echo $newsletter_value; ?>" onclick="unsubscribe();" checked>
        <span class="label-text"></span>
<? } else{ ?>
        <input id="checkbox" type="checkbox" name="checkbox" value="<?php echo $newsletter_value; ?>" onclick="update_newsletter(1);">
        <span class="label-text"></span>
<? } ?>

JavaScript

function unsubscribe(){
    var c = confirm("Are you sure?");
    if(c){
            update_newsletter(0);
    }else{ $('#checkbox').prop('checked',true)}
}

function update_newsletter(newsletter){
    url = '/updateNewsletter&newsletter='+newsletter ;
    $.ajax({
        type: 'get',
        url: url,
        dataType: 'html',
        success: function() { 
            $('#success').append("<div class='alert alert-success'><i class='fa fa-check-circle'></i> You have successfully modified your subscription <button type='button' class='close' data-dismiss='alert'>&times;</button></div>");
        },
        error: function(xhr, ajaxOptions, thrownError) {
           alert(thrownError + "
" + xhr.statusText + "
" + xhr.responseText);
        }
    });
}

Problem

On first page load, page get newsletter_value from controller and show respective checkbox but once user click it and at same time again click, same function will work as on first click (no toggle in functions).

Hope you understand. and thanks for help.

I think the problem is that you never exchange the onclick function of the checkbox. Because as you stated the page is not reloaded. That means that the PHP code is not executed and the function stays the same (because PHP is executed on the server side).

This again means that you would have to exchange the onclick function in the success callback function of the AJAX request.

JavaScript

// ...
$.ajax({
    // ...
    success: function() { 
        $('#success').append("<div class='alert alert-success'><i class='fa fa-check-circle'></i> You have successfully modified your subscription <button type='button' class='close' data-dismiss='alert'>&times;</button></div>");
        $('#checkbox').attr("onclick","update_newsletter(1);");
    },
    // ...
});

The way to change the onclick function is from this post.