Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

Wordpress Ajax problem

Hello I am trying to add a button to my site that will change a value in my database from "0", to "1". The code works fine when I get MY userid but when I try to get the userid of the page I'm looking at it won't get it. I will post my Function, Ajax and Form code.

FUNCTION

add_action( 'wp_ajax_remove_account', 'remove_account' ); function remove_account() { global $wpdb; global $current_user; $user = $current_user->ID; $author = get_queried_object(); $uid = $author->ID; $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->users SET removed = '%d' WHERE ID = '%d'", '1', $uid )); wp_die();
}

AJAX

<script> jQuery(document).ready(function($) {

$('.wordpress-ajax-form2').on('submit', function(e) {
    e.preventDefault();
    var $form = $(this);
    $.post($form.attr('action'), $form.serialize(), function(data) {
    }, 'json');
});

}); </script>

FORM

<form class="wordpress-ajax-form2" method="post" action="<?php echo AJAX_URL; ?>" > <input type="hidden" name="action" value="remove_account" ><br> <center><button id="msgbutton">Remove Account</button></center> </form>

Now if I use the line

$wpdb->query( $wpdb->prepare( "UPDATE $wpdb->users SET removed = '%d' WHERE ID = '%d'", '1', $user ));

it will work fine because it's getting my id, if I use

$wpdb->query( $wpdb->prepare( "UPDATE $wpdb->users SET removed = '%d' WHERE ID = '%d'", '1', $uid ));

it will not work because it will not get the user id. I've been trying to fix this for a while with no luck. I have all my hope in your guys :)

1 Answer

Just an update, when I put $author = get_queried_object(); $uid = $author->ID; it does return the userid of the profile I'm looking at, it's just not being passed somehow. Before, when I used my function as a hook and tied it to isset $_POST, I had no problem. Not sure if this helps someone try to figure out my problem.