To use ajax in WORDPRESS follow this example code:
inputtitle_submit.js:
(function ($) { $(document).ready(function () { $('#next').click(function () { $.post( PT_Ajax.ajaxurl, { // wp ajax action action: 'ajax-inputtitleSubmit', // vars title: $('input[name=title]').val(), // send the nonce along with the request nextNonce: PT_Ajax.nextNonce }, function (response) { console.log(response); } ); return false; }); }); })(jQuery);
inputtitle_submit_inc.php:
<?php add_action( 'wp_enqueue_scripts', 'inputtitle_submit_scripts' ); add_action( 'wp_ajax_ajax-inputtitleSubmit', 'myajax_inputtitleSubmit_func' ); add_action( 'wp_ajax_nopriv_ajax-inputtitleSubmit', 'myajax_inputtitleSubmit_func' ); function inputtitle_submit_scripts() { wp_enqueue_script( 'inputtitle_submit', get_template_directory_uri() . '/js/inputtitle_submit.js', array( 'jquery' ) ); wp_localize_script( 'inputtitle_submit', 'PT_Ajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'nextNonce' => wp_create_nonce( 'myajax-next-nonce' ) ) ); } function myajax_inputtitleSubmit_func() { // check nonce $nonce = $_POST['nextNonce']; if ( ! wp_verify_nonce( $nonce, 'myajax-next-nonce' ) ) { die ( 'Busted!' ); } // generate the response $response = json_encode( $_POST ); // response output header( "Content-Type: application/json" ); echo $response; // IMPORTANT: don't forget to "exit" exit; }
page-ajax_input.php:
<?php /* Template Name: Input Submition Page */ get_header(); ?> <div class="form-signin"> <h2>Input Title</h2> <div class="control-group"> <input type="text" required="required" name="title" class="input-block-level" placeholder="Input Title"> <button class="btn btn-large" id="next">Next</button> </div> </div> <?php get_footer();
Question and answer is powered by AnsPress.io