If you are using ajax in WordPress, you don't need to do it "outside" of WordPress. WordPress has it's own filter hook system which allows for ajax callback functions to be run while having FULL access to all of WordPress's functionality.
Have a look at this:
https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_%28action%29
Here is a complete example of how to set up an ajax callback properly in WordPress:
PHP Code (place in plugin or functions.php file of theme)
//First enqueue your javascript in WordPress
function your_prefix_enqueue_scripts(){
//Enqueue your Javascript (this assumes your javascript file is located in your plugin in an "includes/js" directory)
wp_enqueue_script( 'your_unique_js_name', plugins_url('js/yourjavascriptfile.js', dirname(__FILE__) ), array( 'jquery' ) );
//OR (simpler but not recommended)
wp_enqueue_script( 'your_unique_js_name', 'http://domain.com/myjavascriptfile.js', array( 'jquery' ) );
//Here we create a javascript object variable called "youruniquejs_vars". We can access any variable in the array using youruniquejs_vars.name_of_sub_variable
wp_localize_script( 'your_unique_js_name', 'youruniquejs_vars',
array(
//To use this variable in javascript use "youruniquejs_vars.ajaxurl"
'ajaxurl' => admin_url( 'admin-ajax.php' ),
)
);
}
add_action( 'wp_enqueue_scripts', 'your_prefix_enqueue_scripts' );
//This is your Ajax callback function
function your_ajax_callback_function_name(){
//Get the post data
$username = $_POST["username"];
//Run any WordPress function you want in this ajax callback
if ( username_exists( $username ) ){
$array_we_send_back = array( 'message' => __( 'This user exists', 'textdomain' ) );
}
else{
$array_we_send_back = array( 'message' => __( 'This user does not exist', 'textdomain' ) );
}
//Make sure to json encode the output because that's what it is expecting
echo json_encode( $array_we_send_back );
//Make sure you die when finished doing ajax output.
die();
}
add_action( 'wp_ajax_' . 'your_ajax_callback_function_name', 'your_ajax_callback_function_name' );
add_action( 'wp_ajax_nopriv_' . 'your_ajax_callback_function_name', 'your_ajax_callback_function_name' );
And then this goes in your javascript file:
jQuery(document).ready(function($){
/**
* When your ajax trigger is clicked
*
*/
$( document ).on( 'click', '.my-button', function(event){
event.preventDefault();
// Use ajax to do something...
var postData = {
action: 'your_ajax_callback_function_name',
username: 'test_username_1',
}
//Ajax load more posts
$.ajax({
type: "POST",
data: postData,
dataType:"json",
url: youruniquejs_vars.ajaxurl,
//This fires when the ajax 'comes back' and it is valid json
success: function (response) {
alert( response.message );
}
//This fires when the ajax 'comes back' and it isn't valid json
}).fail(function (data) {
console.log(data);
});
});
});