n this basic plugin skeleton, I am trying to get the data sent by ajax to wordpress admin-ajax.php to be processed by a custom function.
It looks like the data send from the form does not reach my ea_ajax_handler() function. It seems to arrive to admin-ajax.php (the form data is collected by jQuery, then I get a 200 response for the post request to admin-ajax.php), but it looks like it not forwarded to ea_ajax_handler().
Here are my files:
easyA.php:
/** Enqueue scripts */
add_action('wp_enqueue_scripts', 'ea_scripts');
function ea_scripts()
{
wp_enqueue_script('jquery');
// easyA script in the footer
wp_register_script('easyA', plugins_url('js/easyA.js', __FILE__), array('jquery'), '', true);
wp_enqueue_script('easyA'); // wondering if it's really needed or if the previous line is enough...
wp_localize_script('easyA', 'easyAVars', array('ajaxUrl' => admin_url('admin-ajax.php')));
}
/** Shortcode to display form in pages / posts */
add_shortcode('easyA','ea_display_form');
function ea_display_form()
{
echo '
<form id="eaForm">
<input type="text" name="username" />
<input type="submit" value="Submit" />
</form>
';
}
/** Event handling */
add_action('wp_ajax_ea_ajax_handler', 'ea_ajax_handler');
add_action('wp_ajax_nopriv_ea_ajax_handler', 'ea_ajax_handler');
function ea_ajax_handler()
{
$json = array(
'success' => false,
'result' => 0
);
if (isset($_POST['username'])) {
$result = 'Hi, ' . $_POST['username'] . '!';
$json['success'] = true;
$json['result'] = $result;
}
echo json_encode($json);
wp_die();
}
easyA.js:
jQuery(document).ready(function($) {
$('#eaForm').on('submit', function() {
var that = $(this),
contents = that.serialize();
console.log('contents: ' + contents); // debugging
jQuery.ajax({
url: easyAVars.ajaxUrl,
dataType: 'json',
type: 'post',
data: contents,
action: 'ea_ajax_handler', // function in easyA.php that will be triggered
success: function(data) {
console.log(data);
}
});
return false;
});
});
contents.action = 'ea_ajax_handler';
right aftercontents = that.serialize();
didn't work.that.serialize()
doesn't create a jQuery object, it creates a string with form:username=Smith
. So to add the action you'd need to concatenate the string.contents = that.serialize + '&action=ea_ajax_handler
(untested)