Skip to content

Instantly share code, notes, and snippets.

@lunule
Forked from jackreichert/inputtitle_submit.js
Last active April 4, 2023 15:25
Show Gist options
  • Save lunule/59e8d94e67e18172907728077a588caa to your computer and use it in GitHub Desktop.
Save lunule/59e8d94e67e18172907728077a588caa to your computer and use it in GitHub Desktop.
Example showing how to use AJAX in WordPress
(function ($) {
$(document).ready(function () {
$('#next').click(function () {
$.ajax({
type: 'POST',
url: PT_Ajax.ajaxurl,
data: {
// wp ajax action
action: 'ajax-inputtitleSubmit',
// vars
title: $('input[name=title]').val(),
// send the nonce along with the request
nextNonce: PT_Ajax.nextNonce
},
success: function (response) {
console.log(response);
},
error: function(xhr, textStatus, error){
console.log(xhr);
console.log(textStatus);
console.log(error);
}
})
});
});
})(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!' );
}
ob_start();
// (...) => Do something
$new_posts = ob_get_clean();
//wp_send_json_success( $new_posts );
wp_send_json_success( 'Fuck off' );
wp_die();
}
<?php
/*
Template Name: Input Submission 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();
@lunule
Copy link
Author

lunule commented Apr 13, 2018

Edited version of jackreichert's inputtitle_submit.js gist @ https://gist.github.com/jackreichert/5233481


Changes:

  • Gist title changed to ajax_in_wordpress.php
  • $.post updated to $.ajax to have better control over success/error callbacks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment