I am working in WordPress trying to use an ajax request to fetch user data by passing the user id.
I can see that the user id sends correctly via AJAX POST but I am getting an internal error message and I don’t know why.
At first I thought it was because I was trying to fetch some custom fields that I had added to the user profile but even when I simplified my script I am still getting the error message.
Any help is much appreciated!
Front End
$('.author').click(function() {
var id = $(this).attr('id');
var temp = id.split('-');
id = temp[1];
$.ajax({
type: 'POST',
url: 'wp-content/themes/twentyeleven/author_info.php',
data: {id: id},
dataType: 'html',
success: function(data) {
$('#author-bio').html(data);
}
});
return false;
});
author_info.php
$user_id = $_POST['id'];
$forename = get_the_author_meta('user_firstname', $user_id);
$output = $user_id;
echo $output;
Error Message
500 (Internal Server Error) jquery.min.js:4
Mathieu added a hackable approach to intercepting a request and redirecting it, which is fine. I prefer to build out AJAX responses that return
json_encodedarrays.Now we build out the function to handle our ajax requests.
First, we need to define our ajax add_action method ->
We need to use both
add_actionlines here. I won’t get into why. You’ll notice the_ajax_requesthere. This is the ‘action’ that we sent over in our AJAX functiondata: {'action' : 'ajax_request'}. We use this hook to validate our AJAX request, it can be anything you’d like.Next, we’ll need to build out or function
ajax_handle_request.Now let’s build our function to actually get the author meta.
Where [meta_option] is a field provided by WP’s native get_the_author_meta function.
At this point, we’ll now go back to our
success:function(data)and (data) is a reference to thejson_encodedarray we’ve returned. We can now iterate over the object to get our fields and output them into the page as you’d like.