When in WordPress I try to run a php script directly I am redirected to the home page

To use an external script with ajax, you must register an action to trigger it. To do it, you need to use wp_ajax_YourAction and wp_ajax_nopriv_YourAction

add_action('wp_ajax_YourAction', 'myAjaxFunction');
// just a way to quickly print your js
add_action('wp_head', 'print_js');

function print_js(){
    ?><script type="text/javascript" >
            jQuery(document).ready(function($) {
                var data = {
                        action: 'YourAction',
                        fun: '42',

                    };
                $.post(ajaxurl, data, function(response) {
                        console.log(response);
                        var json = $.parseJSON(response);

                        alert('the fun number is'+response.fun);

                });
            });
    </script><?php
}
function myAjaxFunction(){
    if(isset($_POST['fun'])){
        $action = $_POST['fun'];
    }

    switch ($action) {

        case 'fun':
            echo json_encode(array('fun'=>$_POST['fun']+1))
            exit();
        break;

        default:
        break;
}

Depending on how your want to trigger your ajax call and the datas you want to post, this is just a simple example.