I cannot get a redirect working in my custom wordpress plugin. I have a button on a page which triggers an AJAX action which calls a function.
In my function (which is definitely being called as I can see the output "User is not logged in" in my debug log), I have:
error_log("User is not logged in!");
wp_redirect(home_url());
exit();
Things I've tried: Hardcoding the url, Trying other urls, Using exit(); and exit, Using header()
Im not sure why this is not working. Every other similar question has answers saying add exit(); after but that has not worked for me. Thanks.
Edit:
Adapted AJAX callback as follows:
<script>
// Create a function to pick up the link click
jQuery(document).ready(function($) {
$('.button').click(function(e){
e.preventDefault();
console.log("Hi")
jQuery.post(
game_mode_register.ajax_url,
{
'action': 'game-mode-register',
'type': $(this).attr("value")
}.fail(function(response){
console.log("ajax response");
//window.location.href = response.redirect_url
});
);
});
});
Error output: SyntaxError: missing ) after argument list, refering to the line right after the //window.location...
Also, it seems like my wp_redirect is getting picked up but blocked. The Javascript console says:
Blocked loading mixed active content “http://my_website.com/”
I have an SSL certificate that is up to date. Not sure what this means either.
Edit:
Going from direction given by first answer, failed attempts include:
wp_send_json_success( $data );
wp_send_json_error( $data );
wp_send_json( $data );
echo json_encode($data);