admin管理员组

文章数量:1379528

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:

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

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" /> 
</form>
<div id="feedback">
</div>
<?php
}

The jQuery:

jQuery(document).ready(function($)
{
$('#postlesson').submit(ajaxSubmit);
function ajaxSubmit() {
var submitlesson = $(this).serialize();

$.ajax({
type: "POST",
url: MyAjax.ajaxurl,
data: submitlesson,
success: function(data) {
$("#feedback").html(data);
}
});
}

return false;
});

The php:

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

if($wpdb->insert('wp_demo',array(
'dname'=>$name,
'age'=>$age
))===FALSE) {
echo "error";
}
else {
echo "success";
}
die();
}

}

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:

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

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" /> 
</form>
<div id="feedback">
</div>
<?php
}

The jQuery:

jQuery(document).ready(function($)
{
$('#postlesson').submit(ajaxSubmit);
function ajaxSubmit() {
var submitlesson = $(this).serialize();

$.ajax({
type: "POST",
url: MyAjax.ajaxurl,
data: submitlesson,
success: function(data) {
$("#feedback").html(data);
}
});
}

return false;
});

The php:

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

if($wpdb->insert('wp_demo',array(
'dname'=>$name,
'age'=>$age
))===FALSE) {
echo "error";
}
else {
echo "success";
}
die();
}

}
Share Improve this question edited Jun 21, 2018 at 10:32 Evince Development 1236 bronze badges asked May 24, 2014 at 15:08 user1497158user1497158 211 silver badge4 bronze badges 5
  • MyAjax.ajaxurl shouldn't be quoted in your jQuery ajax arguments. – TheDeadMedic Commented May 24, 2014 at 15:16
  • Thanks. I changed that, but it didn't have any effect. – user1497158 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. – TheDeadMedic 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. – user1497158 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) – TheDeadMedic Commented May 24, 2014 at 18:59
Add a comment  | 

2 Answers 2

Reset to default 1

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:

jQuery(document).ready(function(){
jQuery("#submit").click(function(){
var name = jQuery("#dname").val();
var age = jQuery("#age").val();
var File = jQuery("#myfile").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('');  // sets the field back to empty
jQuery('[name="dname"]').val('');
jQuery('[name="myfile"]').val(''); 
});
});

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:

<?php
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>
    </tr>
<input type="button" onclick="add_client();" value="add" />
    </table>
    </form>

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';?>';
        jQuery.ajax({
                url: url,
                type: "POST",
                success: function(mge){
                    if(mge == 0){
                        alert('Error');
                    } else {
                        location.reload();
                        jQuery('#c_res_vl').text('Client added successfully');
                    }
                }
            }); 
    }
</script>

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:

<?php

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';
    }else{
        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';    
        }
    }
}
?>

本文标签: jqueryForm isn39t inserting data into database with ajax plugin