简体   繁体   中英

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM