最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - My function containing a mysql query launched by ajax is not working in wordpress. What am I missing?

programmeradmin4浏览0评论

I am trying to insert rows into a table I've set up based on user's answers. I have made a child theme and a custom template for the page with the form. My issue is that I have no way of knowing what's going wrong where and why the data isn't being inserted. my js onclick function is as follows, and this file is called question_submit.js:

jQuery(document).ready(function(){
    jQuery("#questionSubmit").click(function(){
        alert("clicked");
        jQuery.ajax({
            type: 'POST',
            dataType: 'json',
            url:  my_ajax_object.ajax_url, 
            data: { 
                'action' : 'dbtest',
                'option': 1, 
            },
            success: function(data){
                alert(data);
            }
        });
    })
});

Here is where I enqueue the script:

function my_enqueue() {
      wp_enqueue_script( 'question_submit', get_stylesheet_directory_uri() . '/assets/js/question_submit.js', array('jquery') );
      wp_localize_script( 'question_submit', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
 }
 add_action( 'wp_enqueue_scripts', 'my_enqueue' );

And finally here is the function that's binded to the action:

function dbtesting(){
    
    global $wpdb;
    $data = $_POST['data'];
    //$option = sanitize_text_field($_POST["option"]);
    
    $tableName = 'user_answers';
    $insert_row = $wpdb->insert( 
                    $tableName, 
                    array( 
                        'user_id' => 2, 
                        'module_id' => 3, 
                        'section_id' => 1, 
                        'question_id' => 2,
                        'option_no' => 1, 
                    )
                );
    // if row inserted in table
    if($insert_row){
        echo json_encode(array('res'=>true, 'message'=>__('New row has been inserted.')));
    }else{
        echo json_encode(array('res'=>false, 'message'=>__('Something went wrong. Please try again later.')));
    }
    wp_die();
}
add_action( 'wp_ajax_dbtest', 'dbtesting' );
add_action( 'wp_ajax_nopriv_dbtest', 'dbtesting' );

Both of these functions are in my child theme's functions.php file. Right now I am using hard-coded values jsut to test the functionality, later these values will be dependent on the form answers.

When I click the submit button, there is no change in my table but also no php errors. There is no evidence of the ajax query going through on the XHR section of networks in development tools.

发布评论

评论列表(0)

  1. 暂无评论