dimanche 3 juin 2018

Show checkbox dynamically

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 + "\r\n" + xhr.statusText + "\r\n" + 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.




Aucun commentaire:

Enregistrer un commentaire