Conflict between redirected page and Ajax content

I’ve got a page on my Wordpress site which filters films by genre using Ajax when a user (logged in or not) checks boxes on a filter panel. The results then load accordingly. Below is the script for this:

//filter the films
    jQuery(function($) {
    	filter_data();
    
    	function filter_data() {
    		$('.filter_data').html('<div id="loading" style="" ></div>');
    		var action = 'filter_films';
    
    		var genre = get_filter('genre');
    
    		$.ajax({
    			type: "POST",
    			data: {
    				action: action,
    				genre: genre,
    			},
    			dataType: "html",
    			url: '<?php echo admin_url('admin-ajax.php'); ?>',
    
    			success: function(data) {
    				//alert(this.data);
    				jQuery("#filtered-films").html(data);
    			},
    			error: function(xhr, status, error) {
    				var err = eval("(" + xhr.responseText + ")");
    				alert(err.Message);
    			}
    		});
    		return false;
    	}

I then added in some different roles on the backend and as a security measure setup an automatic redirect to the homepage when a particular user type logs in, as follows:

// Redirect subscriber accounts to homepage
add_action('admin_init', 'redirectSubscribersToHomepage');

function redirectSubscribersToHomepage()
{
	$currentUser = wp_get_current_user();

	if (count($currentUser->roles) == 1 AND $currentUser->roles[0] == 'subscriber') {
		wp_redirect(site_url('/'));
		exit;
	}
}

Unfortunately since implementing this, I’ve found adding a redirect to the Homepage for users when they login breaks the films filters and actually inputs part of the page they’re redirected to in place of the filtered data, as shown in the following screenshot. https://pasteboard.co/Ic1kKcm0n60B.png

I don’t know enough about Ajax at this stage to work out what the problem is exactly but it’s like the page is working like an iframe and trying to place the Homepage content into the “filtered-films” element.

If anyone has any thoughts I’d really appreciate it!

Many thanks.

Hi all,

Can anyone think of an alternative for the redirect, or even a fix for the conflict between the redirect and the jQuery HTML input please?

Many thanks!

I don’t think js will recognise php code; but I could be wrong.
And even if it does it is not a good idea to embed it into js.

Thanks for the reply Dennis - do you think this is what is causing the Homepage to appear within the filtered data section, or is it unrelated?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.