I've been working at this for weeks without success. I've figured out problem after problem with the code, but none of the corrections seem to fix my core problem. The form doesn't insert anything into the database and I don't know why. In this particular example, submit results in going to the following URL: (myurl)/?dname=kl&age=56&action=postlesson. The homepage is what loads. I am piecing this together from examples and tutorials on the web.

I'm new to ajax and to WordPress plugins so I might be missing something obvious. Please help me know where I am going wrong.

The enqueues:

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')));

The form:

public function show_form(){
<form type="post" name="submitlesson" action="" id="submitlesson">
<input type="text" name="dname" id="dname" />
<input type="age" name="age" id="age" />
<input type="hidden" name="action" value="postlesson" />
<input type="submit" /> 
<div id="feedback">

The jQuery:

function ajaxSubmit() {
var submitlesson = $(this).serialize();

type: "POST",
url: MyAjax.ajaxurl,
data: submitlesson,
success: function(data) {

return false;

The php:

public function postlesson(){
global $wpdb;
$name = $_POST['dname'];
$age = $_POST['age'];

))===FALSE) {
echo "error";
else {
echo "success";

  • MyAjax.ajaxurl shouldn't be quoted in your jQuery ajax arguments. Commented May 24, 2014 at 15:16
  • Thanks. I changed that, but it didn't have any effect. Commented May 24, 2014 at 15:19
  • Use a HTTP inspector like HttpFox to check the data is correctly sending to the correct URL and see what the server is responding with. Commented May 24, 2014 at 15:21
  • I don't really know how to make sense of some of the debugger tools, but from what I can tell, when I click submit, it does run the demo.js from the correct path, but I get "none" for POST data and 304 not modified for the status line of the script under response header. I don't see admin-ajax.php though under scripts responding and I'm wondering if I should. Thanks for the help with this. Commented May 24, 2014 at 15:37
  • Yes, you should. Check that MyAjax.ajaxurl is the correct URL - use a JavaScript alert or a browser console. Next make sure that your demo.js isn't cached (usually F5 in a browser) Commented May 24, 2014 at 18:59

2 Answers 2


I never did figure out how to do this with serialize or formData, but I figured out two other ways to do it. The easiest is to just skip this step altogether and in the action and js url list the url to a php file like you might do if you weren't in wordpress. I then added this line to the top of it and it worked. require_once( '../../../wp-load.php' ); This is unadvised because of server load and some other reasons I don't fully understand, but it works.

The second way, if you don't need to serialize or upload a file, is to do this:

var name = jQuery("#dname").val();
var age = jQuery("#age").val();
var File = jQuery("#myfile").val();
type: 'POST',   // Adding Post method
url: MyAjax.ajaxurl, // Including ajax file
data: {"action": "postlesson", "dname":name, "age":age, "myfile":File}, // Sending data dname to post_word_count function.
success: function(response){ // Show returned data using the function.
jQuery('[name="age"]').val('');  // sets the field back to empty

I'm just posting this in case someone as clueless as me comes looking. This all meant changing the form too. I don't have that code ready, but essentially, I just got rid of the hidden submit field.


Check out this example. I have the form with one field (text field) with the submit button:

global $wpdb; //Declare to interact with the database
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<h3>Add New Client</h3>
<table class="form-table">
    <tr class="form-field">
        <th scope="row"><label for="cname"><?php _e('Client Name'); ?> </label></th>
        <td><input name="client_name" type="text" id="client_name" value="" aria-required="true" autocapitalize="none" autocorrect="off" /></td>
<input type="button" onclick="add_client();" value="add" />

Using Ajax to pass this value to the PHP page:

<script type="text/javascript">
    function add_client(){
        var url = '<?php echo admin_url().'add.php';?>';
                url: url,
                type: "POST",
                success: function(mge){
                    if(mge == 0){
                    } else {
                        jQuery('#c_res_vl').text('Client added successfully');

This PHP code is used to check if the data exists in the database and if it exists, then it overwrites. Create a file called add.php and add this code:


if(!empty($_POST['client_name']) && isset($_POST['client_name'])) {
    $client_name = $_POST['client_name'];

//global $wpdb;
if(isset($client_name) && !empty($client_name)){
    $query = $wpdb->get_row("SELECT * FROM `wp_clients` WHERE `client_name`='".$client_name."'");

    if (!empty($query->client_id)) {
        echo 'Client already exists';
        if($client_name != 'None'){
            $sql = $wpdb->prepare("INSERT INTO `wp_clients`(`client_name`) VALUES ('".$client_name."')");

            if ($wpdb->query($sql)) {
                echo "New client created successfully";
            } else {
                echo "Error: " . $sql . "<br>" . $wpdb->error;
        }else {
            echo 'Please enter the client name';    

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.