javascript
jQuery(document).ready(function($) { // We'll pass this variable to the PHP function example_ajax_request $('.fl-slide-photo').click(function(){ var fruit = 'Banana'; var security = gs_frontend_ajax_object.security // This does the ajax request $.ajax({ url: gs_frontend_ajax_object.ajax_url, // or example_ajax_obj.ajaxurl if using on frontend data: { 'action': 'gs_frontend_ajax', 'fruit' : fruit, 'security': security }, success:function(data) { // This outputs the result of the ajax request console.log(data); }, error: function(errorThrown){ console.log(errorThrown); } }); }); });
php
<?php /** * Plugin Name: Ajax Test * Plugin URI: * Description: This is a plugin that allows us to test Ajax functionality in WordPress * Version: 1.0.0 * Author: * Author URI: * License: GPL2 */ add_action( 'wp_enqueue_scripts', 'example_ajax_enqueue' ); function example_ajax_enqueue() { wp_enqueue_script('gs_frontend_ajax',plugins_url( '/test.js', __FILE__ ),array('jquery'),false,true); wp_localize_script('gs_frontend_ajax', 'gs_frontend_ajax_object', array( 'ajax_url' => admin_url('admin-ajax.php'), 'security' => wp_create_nonce('ajaxnonce') )); } add_action( 'wp_ajax_gs_frontend_ajax', '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_gs_frontend_ajax', 'example_ajax_request' ); function example_ajax_request() { // The $_REQUEST contains all the data sent via ajax $action = $_REQUEST['action']; $nonce = $_REQUEST['_wpnonce']; if ( $action == 'gs_frontend_ajax' && wp_verify_nonce( $nonce, 'ajaxnonce' ) == $nonce){ // && wp_verify_nonce( $nonce, 'ajaxnonce' ) $fruit = $_REQUEST['fruit']; $security = $_REQUEST['security']; // 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(); }