Skip to content

Instantly share code, notes, and snippets.

@jackreichert
Last active September 26, 2020 15:03
Show Gist options
  • Save jackreichert/5233481 to your computer and use it in GitHub Desktop.
Save jackreichert/5233481 to your computer and use it in GitHub Desktop.
Example showing how to use AJAX in WordPress
(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);
<?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;
}
<?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();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment