Skip to content

Instantly share code, notes, and snippets.

@newsapkota
Forked from jackreichert/inputtitle_submit.js
Created March 30, 2018 16:19
Show Gist options
  • Save newsapkota/7a1a9fd414c9da345be4f683320739b6 to your computer and use it in GitHub Desktop.
Save newsapkota/7a1a9fd414c9da345be4f683320739b6 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