mardi 28 juillet 2015

Ajax: convert checkbox function to input field and update button in Wordpress

The checkbox has only 2 values: 0 and 1. But what i'm trying to do is to put date and time in the text input (instead of the checkbox) and than to update it with submit button Update with Ajax. Any help please to convert a checkbox to input field and update button like this:

<input id="post_author_credit_update" name="post_author_credit" value="2015-08-22 11:00 PM" type="text"/>';
<input id="post_author_credit_update" name="post_author_credit" type="submit" class="button updatemeta button-small"  value="Update"/>

The actual checkbox

<input id="post_author_credit_update" name="post_author_credit" value="1" type="checkbox"<?php checked( get_post_meta( $post->ID, 'post_author_credit', true ), 1, false ); ?>/>

And the script responsible for saving the value:

 function ajax_save_post_author_credit() {

    // Verify that the incoming request is coming with the security nonce
    if( wp_verify_nonce( $_REQUEST['nonce'], 'ajax_post_author_credit_nonce' ) ) {

        // Set the value of the post meta based on the post data coming via the JavaScript
        $post_author_credit = '';
        if( isset( $_POST['post_author_credit'] ) && 'true' == $_POST['post_author_credit'] ) {
            $post_author_credit = 1;
        } // end if

        // Attempt to update the post meta data. If it succeeds, send 1; otherwise, send 0.
        if( update_post_meta( $_POST['post_id'], 'post_author_credit', $post_author_credit ) ) {
            die( '1' );
        } else {
            die( '0' );
        } // end if/else

    } else {

        // Send -1 if the attempt to save via Ajax was completed invalid.
        die( '-1' );

    } // end if 

 } // end ajax_save_post_author_credit
} // end class
new Post_Author_Credit();

../plugins/post-author/js/admin.js:

(function($) {
$(function() {
    $('#post_author_credit_update').click(function(evt) {

        $.post(ajaxurl, {
            action:             'save_post_author_credit',
            nonce:              $('#ajax_post_author_credit_nonce').text(),
            post_id:            $('#post_ID').val(),
            post_author_credit: $(this).is(':checked')

            }, function(response) {
                $( "#ajax_response" ).text( "UPDATED" ).show().fadeOut( 1000 );
        });
    });
});
})(jQuery);

Thanks in advance.




Aucun commentaire:

Enregistrer un commentaire