-
-
Save vicso-name/83420febc178aaadc4ec31a0609a6365 to your computer and use it in GitHub Desktop.
Simple WordPress Ajax Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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','wp-util') | |
); | |
} | |
add_action( 'wp_enqueue_scripts', 'example_ajax_enqueue' ); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
jQuery(document).ready(function($) { | |
// We'll pass this variable to the PHP function example_ajax_request | |
var fruit = 'Banana'; | |
// Send the form via ajax | |
wp.ajax.send( "example_ajax_request", { | |
success:function(data) { | |
// This outputs the result of the ajax request | |
console.log(data); | |
}, | |
error: function(errorThrown){ | |
console.log(errorThrown); | |
}, | |
data: { | |
'fruit' : fruit | |
} | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
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' ); | |
function example_ajax_request() { | |
// The $_REQUEST contains all the data sent via ajax | |
if ( isset($_REQUEST) ) { | |
$fruit = $_REQUEST['fruit']; | |
// Send the data back to Javascript. | |
wp_send_json_success( $_REQUEST ); | |
} | |
//if send an error. | |
wp_send_json_error( $_REQUEST ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment