Here is how you can use the joomla jfactory library on external file or ajax, just include this 2 file then you can already use the jfactory on that page.

define( ‘_JEXEC’, 1 );
require_once(‘../../../../libraries/import.php’ ); // framework
require_once(‘../../../../configuration.php’ ); // config file

$db = JFactory::getDBO();  // this will now work fine on the external php file