Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress: call to plugin php file via ajax

I wrote a wordpress plugin witch appends some comment functions in my template. Via ajax all the stuff should be transmitted into the wordpress database.

The problem is - the ajax handler needs a php file with captures the query via

if(isset($_POST['name'], $_POST['title'], $_POST['description'])) { 

 // do something with wordpress actions, e.g. get_current_user, $wpdb

}

At the time the user transmits the query the ajax handler calls the php file like this:

$('#ajax_form').bind('submit', function() {
    var form = $('#ajax_form');
    var data = form.serialize();
    $.post('../wp-content/plugins/test/getvars.php', data, function(response) {
        alert(response);           
    });
    return false; 

The getvars.php doesn't know the wordpress environment because it is called directly from user submit and I think to add the wordpress environment classes and includes is not the good style.

Is there any other way? Thanks for support.

like image 796
creality Avatar asked Mar 27 '13 21:03

creality


1 Answers

yes use the builtin wordpress ajax actions:

your jquery will look like this:

$('#ajax_form').bind('submit', function() {
    var form = $('#ajax_form');
    var data = form.serialize();
    data.action = 'MyPlugin_GetVars'
    $.post('/wp-admin/admin-ajax.php', data, function(response) {
        alert(response);           
    });
return false; 

your plugin code something like:

add_action("wp_ajax_MyPlugin_GetVars", "MyPlugin_GetVars");
add_action("wp_ajax_nopriv_MyPlugin_GetVars", "MyPlugin_GetVars");

function MyPlugin_GetVars(){
    global $wpdb;
    // use $wpdb to do your inserting

    //Do your ajax stuff here
    // You could do include('/wp-content/plugins/test/getvars.php') but you should
    // just avoid that and move the code into this function
}
like image 84
DiverseAndRemote.com Avatar answered Sep 25 '22 04:09

DiverseAndRemote.com