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