0

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.

  • Read and adapt the following example: [How to Use AJAX in a WordPress Shortcode?](http://stackoverflow.com/a/13614297/1287812) – brasofilo May 19 '14 at 16:51
  • Thanks for your response. I appreciate you taking the time. I'll try to come back to that to see if it helps me as a reference down the line, but I am so lost about what is causing the issue in my code that I don't know which part of your script I should be looking at. I read it and I modified the data to add action: , but it had no effect. I don't know if I'm missing code or if I am executing what I have incorrectly. – user1497158 May 20 '14 at 03:26
  • The enqueues are on the "air", they should be inside a proper action, `wp_enquque_scripts`. The ajax `data` is wrong. – brasofilo May 20 '14 at 04:07
  • Thanks for the feedback. I keep getting errors on plugin.php when I add action to wp_enqueue_scripts, but I'm reading and working on it. Is this what is causing the problem or is it just that putting it in an action is a better way to do it? I do see my demo.js script in the source code. – user1497158 May 20 '14 at 16:53
  • possible duplicate of [How to Use AJAX in a WordPress Shortcode?](http://stackoverflow.com/questions/13498959/how-to-use-ajax-in-a-wordpress-shortcode) – brasofilo May 20 '14 at 17:10
  • I just realized about the duplicate. You'll have to adapt `wp_localize_script`, `get_random_post()` and the JS file. – brasofilo May 20 '14 at 17:11
  • Thanks. This didn't turn out to be part of the issue, but at least I know my enqueues aren't sloppy now. I learned a lot while trying to take apart understand that code too, although it didn't help me fix this problem. Also, I ended up needing to enqueue a lot more, so this really simplified things for me later. Much appreciated. – user1497158 May 28 '14 at 06:52

2 Answers2

1

You have not passed the action value in the JS ajax code.

Your JS code needs to be

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;
}

Also confirm the table name where you are inserting the record is the same one in the code

0

In case anyone has a similar issue and is trying to learn all of this a bit at a time. I eventually worked my way around this by avoiding serializing the data. I never did figure out to get the action part right when it was serialized or in formData, but this works:

jQuery(document).ready(function(){
jQuery("#submit").click(function(){
var name = jQuery("#dname").val();
var age = jQuery("#age").val();
jQuery.ajax({
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("#feedback").html(response);
}
});
jQuery('[name="age"]').val('');   // empties the field after submit
jQuery('[name="dname"]').val('');
});
});

As an added note, it turns out that I didn't need to process this through the plugin function page at all. I needed to upload a file along with submitting this data which meant using formData, but I couldn't get the action element right, so I just set url to a php file within the plugin folder instead of ajaxurl and it worked. I needed one line of code for that at the top of the php file: require_once( '../../../wp-load.php' );

It's not pretty. I'd rather have sent it through the action function, but this got it done.

  • See [***Don't include wp-load.php, please***](http://ottopress.com/2010/dont-include-wp-load-please/) – brasofilo May 28 '14 at 06:59
  • 1
    I'm using this plugin just for my own website and only on the one page when submit is clicked, so the path isn't an issue. I'd rather do it the right way, but I can't get it to work. It seems like for my specific usage, it will be ok. I did see that wp-load was to be avoided though...then I forgot because I got happy that it worked... Thanks for reminding me and others who might read so they know. – user1497158 May 28 '14 at 07:21