Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple WordPress Ajax Example
<?php
function example_ajax_enqueue() {
// Enqueue javascript on the frontend.
wp_enqueue_script(
'example-ajax-script',
get_template_directory_uri() . '/js/simple-ajax-example.js',
array('jquery')
);
// The wp_localize_script allows us to output the ajax_url path for our script to use.
wp_localize_script(
'example-ajax-script',
'example_ajax_obj',
array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce('ajax-nonce')
)
);
}
add_action( 'wp_enqueue_scripts', 'example_ajax_enqueue' );
jQuery(document).ready(function($) {
// We'll pass this variable to the PHP function example_ajax_request
var fruit = 'Banana';
// This does the ajax request
$.ajax({
url: example_ajax_obj.ajaxurl,
data: {
'action': 'example_ajax_request',
'fruit' : fruit,
'nonce' : example_ajax_obj.nonce
},
success:function(data) {
// This outputs the result of the ajax request
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
});
<?php
function example_ajax_request() {
$nonce = $_POST['nonce'];
if ( ! wp_verify_nonce( $nonce, 'example-ajax-script' ) ) {
die( 'Nonce value cannot be verified.' );
}
// The $_REQUEST contains all the data sent via ajax
if ( isset($_REQUEST) ) {
$fruit = $_REQUEST['fruit'];
// Let's take the data that was sent and do something with it
if ( $fruit == 'Banana' ) {
$fruit = 'Apple';
}
// Now we'll return it to the javascript function
// Anything outputted will be returned in the response
echo $fruit;
// If you're debugging, it might be useful to see what was sent in the $_REQUEST
// print_r($_REQUEST);
}
// Always die in functions echoing ajax content
die();
}
add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );
// If you wanted to also use the function for non-logged in users (in a theme for example)
add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' );
@merithes
Copy link

merithes commented Oct 9, 2018

Would you mind giving an HTML demo so I get it to work and then try to tweak it ?

@surajkhanal
Copy link

surajkhanal commented Sep 21, 2019

If you have added the nonce validation part, that would be awesome. Anyway thanks for the snippet.

@zohaib87
Copy link

zohaib87 commented Nov 4, 2019

Thank you so much!

@jssdesarrollo
Copy link

jssdesarrollo commented Dec 10, 2019

Thank you Devinsays. It was very helpfull to me.

@salvatorecapolupo
Copy link

salvatorecapolupo commented Mar 25, 2020

using:

echo json_encode($_REQUEST);

you can return JSONified output as usually requested.

@Peps03
Copy link

Peps03 commented Mar 29, 2020

If you have added the nonce validation part, that would be awesome. Anyway thanks for the snippet.

Agree!

@devinsays
Copy link
Author

devinsays commented May 4, 2020

Updated the gist to include the nonce validation. Hope that's helpful.

@freelancedaddytv
Copy link

freelancedaddytv commented Jul 21, 2020

Updated the gist to include the nonce validation. Hope that's helpful.

it is giving 400 bad error in the latest WordPress version

@erikbml
Copy link

erikbml commented Jul 28, 2020

@jefreylandicho

Updated the gist to include the nonce validation. Hope that's helpful.

it is giving 400 bad error in the latest WordPress version

I had the same thing - first because I didn't had the handler function "example_ajax_request" implemented correctly

After that, I got that error because I was using the nopriv when logged in (or the other way around). When following the code correctly, it did work in the end.

@mTeden
Copy link

mTeden commented Dec 2, 2020

I can't get it to work. It's always returning Error 400 Bad Request.

  • function example_ajax_enqueue() {...} => functions.php (in theme directory with path checked at line 7)
  • js file (with permissions checked - 0755)
  • calling simple-ajax-example.php

Error:
jquery.js?ver=1.12.4-wp:4 GET wp-admin/admin-ajax.php?action=example_ajax_request&fruit=Banana&nonce=ae030e8819 400 (Bad Request)

Wordpress: 5.5.3
Theme: Directory2 (AIT-Themes)

@simpletome
Copy link

simpletome commented Dec 2, 2020

wp_verify_nonce( $nonce, 'example-ajax-script' ) should be wp_verify_nonce( $nonce, 'ajax-nonce' )
And your ajax request is missing method/type as post e.g method: "POST"

@gleenk
Copy link

gleenk commented Nov 24, 2021

wp_verify_nonce( $nonce, 'example-ajax-script' ) should be wp_verify_nonce( $nonce, 'ajax-nonce' ) And your ajax request is missing method/type as post e.g method: "POST"

He's right!

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