Test if php document executed by WordPress or directly

You should never need to send a user or a form or an AJAX request directly to a plugin files URL.

If you’re submitting a form, no new URL is needed at all, simply:

if ( !empty( $_POST['formfield'] ) {
    // handle form submission and print thank you
} else {
    // display form
}

Or as most people do, use gravity forms or a plugin such as contact7

If you’re doing an AJAX call, use the provided API for AJAX calls

PHP:

function example_ajax_request() {
    if ( isset($_REQUEST) ) {
        $fruit = $_REQUEST['fruit'];
        if ( $fruit == 'Banana' ) {
            $fruit="Apple";
        }
        echo $fruit;
    }
    // Always die in functions echoing ajax content
   die();
}
add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );
add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' );

Javascript

jQuery(document).ready(function($) {
    // We'll pass this variable to the PHP function example_ajax_request
    var fruit="Banana";
    // This does the ajax request
    $.ajax({
        url: ajaxurl,
        data: {
            'action':'example_ajax_request',
            'fruit' : fruit
        },
        success:function(data) {
            // This outputs the result of the ajax request
            console.log(data);
        },
        error: function(errorThrown){
            console.log(errorThrown);
        }
    });
});

Notes on WP AJAX

The only time you should test if the file is being loaded as you requested, is so that you can immediatley exit the script to avoid security concerns.

E.g.

if ( !defined( 'WPINC' ) ) {
    die();
}

Faster AJAX calls

The standard AJAX caller can sometimes be under-performant when doing things on super high traffic sites, in this case, I defer to Rarsts answer here:

Ajax takes 10x as long as it should/could

But even in that case, I would not have a single file handle both the AJAX and the non-AJAX, it’s poor separation of concerns. Your AJAX handler should be a separate dedicated file if it isn’t using the WP AJAX APIs.