0

how to insert data in wordpress using jquery ajax for my plugin, i tried a lot but my action.php page not access global $wpdb, Please tell me where is the problem.

Here is the code of my submenu page of plugin

<?php
        function pincode()
        {
        ?>   

        <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
        <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
        <script>
        function userAction(type,id){
            id = (typeof id == "undefined")?'':id;
            var statusArr = {add:"added",edit:"updated",delete:"deleted"};
            var userData = '';
            if (type == 'add') {
                userData = $("#addForm").find('.form').serialize()+'&action_type='+type+'&id='+id;
            }else if (type == 'edit'){
                userData = $("#editForm").find('.form').serialize()+'&action_type='+type;
            }else{
                userData = 'action_type='+type+'&id='+id;
            }
            $.ajax({
                type: 'POST',
                //url: 'http://localhost/wordpress/wp-content/plugins/arunkumar/action.php',
                url : '<?php echo plugin_dir_url(__FILE__).'action.php';?>',
                data: userData,
                success:function(msg){
                    if(msg == 'ok'){
                        alert('User data has been '+statusArr[type]+' successfully.');
                        //getUsers();
                        $('.form')[0].reset();
                        $('.formData').slideUp();
                    }else{
                        //alert('Some problem occurred, please try again.');
                        $("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> &nbsp; '+msg+' !</div>');
                    }
                }
            });
        }
        </script>
                <div class="panel-heading">States <a href="javascript:void(0);" class="glyphicon glyphicon-plus" id="addLink" onclick="javascript:$('#addForm').slideToggle();"></a></div>
                <div class="panel-body none formData" id="addForm">
                    <h2 id="actionLabel">Add New State</h2>
                    <form class="form" id="userForm">
                        <div id="error"></div>
                        <div class="form-group">
                            <label>State Name</label>
                            <input type="text" class="form-control" placeholder="Enter State Name" name="name" id="name"/>
                        </div>

                        <a href="javascript:void(0);" class="btn btn-warning" onclick="$('#addForm').slideUp();">Cancel</a>
                        <a href="javascript:void(0);" class="btn btn-success" onclick="userAction('add')">Add State</a>
                    </form>
                </div>
    <?php
    }

and this is action.php code where insert code is applied but it show " Fatal error: Call to a member function insert() on null " error

    <?php

    if(isset($_POST['action_type']) && !empty($_POST['action_type'])){
        if($_POST['action_type'] == 'add'){
            //echo $insert?'ok':'err';
            global $wpdb;
            $state_name = $_POST['name']; 
            $wpdb->insert( 'state',array( 'state_name' => $state_n),array('%s') );
            $status = $wpdb->insert_id;
            echo $status ? 'ok' : var_dump($wpdb);


        }
  • Where are you adding the second block of code? Directly to the page or as a wp_ajax action? – Pedro Coitinho Jan 18 '17 at 12:32
  • Hi @PedroCoitinho i'm adding second block of coding on another page name action.php in my plugin,but on action.php $wpdb not working – Arun Kumar Jan 18 '17 at 15:44
4

The code you have shared can work in core PHP and not in Wordpress. Using AJAX in Wordpress plugin is explained in Wordpress documentation. Please refer - https://codex.wordpress.org/AJAX_in_Plugins

I have tried this and it works well.

  • 1
    Nothing better than the codex reference. Should be accepted. – prosti Jan 18 '17 at 13:16
1

looks like Ravi Shinde is right:

The code you have shared can work in core PHP and not in Wordpress. Using AJAX in Wordpress plugin is explained in Wordpress documentation. Please refer - https://codex.wordpress.org/AJAX_in_Plugins

To give your plugin access to the ajax interface you need to wrap it around WordPress' AJAX action wp_ajax_{action}

First, you need to define the action:

add_action( 'wp_ajax_user_action', 'user_action' );
add_action( 'wp_ajax_nopriv_user_action', 'user_action' );

Which registers the user_action with wordpress for both logged in and not authenticated users.

Then you build your handling function:

function user_action() {
    // since this gets loaded by wordpress
    // you get access to $wpdb and other
    // core functions
    global $wpdb; 

    $state_name = $_POST['name']; 

    $wpdb->insert( 'state',array( 'state_name' => $state_n),array('%s') );
    $status = $wpdb->insert_id;

    echo $status ? 'ok' : var_dump($wpdb);

    // Ajax calls in WP always need to be closed with wp_die:
    wp_die(); 
}

Finally, you need to get a reference the endpoint ( wordpress shares a single URL for all ajax calls ). In your JS:

var ajaxurl = <?php echo admin_url( 'admin-ajax.php' ); ?>;

Note: The "correct" way to register scripts is through enqueue_scripts, but thats beyond our scope right now.

Then you can do a regular Ajax call to ajaxurl and passing { action: 'user_action' } as data.

Truth be told its not the best way, but you get used to it. If you need a primer, Smashinmag always has great articles:

https://www.smashingmagazine.com/2011/10/how-to-use-ajax-in-wordpress/

( Also: I haven't tested the code but is pretty standard and should work out of the box. Lemme know! )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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