Wordpress: calling php file plugin via ajax

I wrote a wordpress plugin that adds some comment features to my template. Through ajax, all data should be transferred to the wordpress database.

The problem is that the ajax handler needs a php file to capture the request through

if(isset($_POST['name'], $_POST['title'], $_POST['description'])) { // do something with wordpress actions, eg get_current_user, $wpdb } 

While the user is submitting the request, the ajax handler calls the php file as follows:

 $('#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; 

getvars.php does not know the wordpress environment, because it is called directly from the submit user, and I think that adding classes to the Wordpress environment does not include a good style.

Is there another way? Thanks for the support.

+4
source share
1 answer

yes use ajax built-in actions for wordpress:

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 is 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 } 
+8
source

All Articles