I have a custom js file that runs in the head of my WordPress installation successfully. I need to run an jQuery post request from this file to a PHP file so I can return a value from the database.
-
Where do I create the PHP function? I have used the functions.php file to add the custom js file to start with, but I don’t want this new function to run every page load, just when requested.
-
Once I’ve created the PHP function wherever, how do I access it through the JQuery post request? I’m used to using local paths but WordPress screws all that up!
I’m finding my feet in WordPress. I am a reasonably capable developer normally in codeIgniter etc but WordPress just seems to make everything so obscure and overly complicated! Any help appreciated!
EDIT ————-
I have now created a custom functions file in the plugins folder as per this article) so now I need to know how to access a function within this file from the js file in the header!
If I understand correctly, you are trying to use jQuery to do a HTTP POST request back to your WordPress app when some event happens in the browser. This is a technique known as AJAX (Asynchronous Javascript and XML). Javascript in your browser communicates with a server without refreshing the page and can do more logic you want (in Javascript/jQuery) based on the response from the server. The server can response with more than just XML these days (JSON is pretty popular).
AJAX in WordPress: Standard XML response
AJAX in WordPress Plugins: Response using jQuery. You can do this in a theme instead of a plugin. This is probably what you are looking for.
Edit: A straightforward AJAX example using jQuery and WordPress.
You can use a extension or a 3rd party wordpress analyzer to use this.