I'm having trouble getting AJAX and jQuery to work with WP, and wondering if someone can point me in the right direction.
I have a form, and I want to pass the data from the form to a PHP function, where the data is returned and a <div>
is created with the data manipulated by a PHP function. I've got a version working outside of WP, but I can't seem to port it.
I've followed many tutorials, and nothing seems to work. I've got the following code, it should simply create an alert window with the data from the form , with "hello" prepended, but the JS function never even gets called. It keeps adding ?name=name
to the page URL.
I've also tried creating a seperate JS file, and loading the script with..
wp_enqueue_script(
'myaddwordscript',
plugins_url() . '/MyPlugin/script.js',
array( 'jquery' )
Any help getting it to work is greatly appreciated.
<?php
/**
* Plugin Name: Addword
* Plugin URI: Addword
* Version: 1.0
*/
/**
* Make sure jquery is loaded
*/
function add_to_header() {
wp_enqueue_script('jquery');
}
add_action( 'wp_enqueue_scripts', 'add_to_header' );
/**
* Add shortcode to show form and script
*/
function add_word( ) {
$script = "
<script>
jQuery('#ajax_form').bind('submit', function() {
alert('clicked');
var form = jQuery('#ajax_form');
var data = form.serialize();
data.action = 'add_word_to_form'
jQuery.post('/wp-admin/admin-ajax.php', data, function(response) {
alert(data);
});
return false;
});
</script>";
$form ='
<form class="form" id="ajax_form">
<input type="text" name="name" id="name" placeholder="Word Goes Here" required="">
<input type="submit" value="Submit" id="submitaddword">
</form>';
return $script.$form;
}
add_shortcode( 'addword', 'add_word' );
/**
* Set up AJAX call to add word
*/
add_action("wp_ajax_add_word_to_form", "add_word_to_form");
add_action("wp_ajax_nopriv_add_word_to_form", "add_word_to_form");
function add_word_to_form ($data)
{
return "Hello".$data;
}
?>
alert('clicked');
as the first line in the .bind function, before grabbing the form data, the alert never opens.