If you are intent on calling into Wordpress functionality from outside of the usual WP workflow, you can put the following two lines in your code:
Of course, the above assumes I'm calling this from within a root theme or plugin folder (the
../ indicates reverse folder traversal). It looks as though you've already included
wp-blog-header.php, and the define is an indication to Wordpress not to invoke certain functionality related to normal page/post queries. For an example of how Wordpress functionality can be implemented in a disparate PHP codebase, I would suggest you look at this Laravel+Wordpress post or similar attempts to utilize Wordpress functionality from outside of Wordpress itself. If you need the functionality Wordpress offers (including that of its activated plugins) this might be the best solution.
Otherwise, depending on your scenario, invoking Wordpress code as Ajax, as suggested by other users, may be the appropriate route to go. In particular, if you wanted to implement a simple CRUD API, such as a RESTful operation, this would be the suggested route. This is the route I would personally recommend if all you are interested in doing is moving data from points A and B.
Your code may have failed because you didn't define the
WP_USE_THEMES flag properly; under normal circumstances, functionality offered by plugins isn't available until after a certain point (probably the
init action, based on http://codex.wordpress.org/Plugin_API/Action_Reference), and trying to call plugin functionality before that action has occurred may result in what you describe.