I've read everything I can find from searching and there are a lot of answers out there, but I can't make sense of any of them with the code I'm using. I need to know what I'm doing wrong. The biggest issue is that I'm an amateur and ajax is way outside of my knowledge base.
The code I'm putting up here is essentially exactly what I got from this tutorial http://www.makeuseof.com/tag/tutorial-ajax-wordpress/. I've made the upload work with another similar code from here: http://www.inkthemes.com/how-to-use-ajax-in-wordpress-for-data-insertion/08/, but I couldn't make the fields clear later. I thought this version might make that less of a hassle for some reason. I would appreciate links to tutorials on this or answers to questions I haven't found yet, but mostly I want to know why this isn't working, so I can understand what is happening.
When I click submit, the page moves to myurl/?name=saldkfl&action=postlesson&s= and nothing gets inserted into the database.
This is my form:
public function show_form(){
?>
<form type="post" name="submitlesson" action="" id="submitlesson">
<input type="text" name="name" id="name" />
<input type="age" name="age" id="age" />
<input type="hidden" name="action" value="postlesson"/>
<input type="submit" />
<div id="feedback">
</div>
<?php
}
This is php code add_action( 'plugins_loaded', array ( B5F_SO_13498959::get_instance(), 'plugin_setup' ) );
class B5F_SO_13498959
{
private $cpt = 'post'; # Adjust the CPT
protected static $instance = NULL;
public $plugin_url = '';
public function __construct() {}
public static function get_instance()
{
NULL === self::$instance and self::$instance = new self;
return self::$instance;
}
/**
* Regular plugin work
*/
public function plugin_setup()
{
$this->plugin_url = plugins_url( '/', __FILE__ );
add_shortcode('the_content', array($this, 'show_form'));
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue' ) );
add_action( 'wp_ajax_postlesson', array( $this, 'postlesson' ) );
add_action( 'wp_ajax_nopriv_postlesson', array( $this, 'postlesson' ) );
}
public function enqueue()
{
//Include Javascript library
wp_enqueue_script('lessonupload', "{$this->plugin_url}demo.js" , array( 'jquery' ));
// including ajax script in the plugin Myajax.ajaxurl
wp_localize_script( 'lessonupload', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php')));
}
public function postlesson(){
global $wpdb;
$name = $_POST['name'];
$age = $_POST['age'];
if($wpdb->insert('wp_demo',array(
'name'=>$name,
'age'=>$age
))===FALSE) {
echo "error";
}
else {
echo "success";
}
die();
}
}
my jQuery
jQuery('#submitlesson').submit(ajaxSubmit);
function ajaxSubmit () {
var submitlesson = jQuery(this).serialize();
jQuery.ajax({
type: 'POST',
url: 'MyAjax.ajaxurl',
data: ({action : 'postlesson'}),
success: function(data){
jQuery("#feedback").html('data');
}
});
return false;
}
Please help! Thank you.