Reputation: 967
I'm using a lot of AJAX calls where I'll say,
data: {action: "get_categories", etc..}
and then in my PHP I'll say,
if(isset($_POST['action']) && ($_POST['action'] == 'get_categories')) {
//do stuff
}
I'm trying to refactor the code a bit, and I'd like to take the output of one of these code blocks and pass it into another one, but its not a PHP function, so I'm not really sure how to do that? Is there a way to call a PHP function directly from the AJAX call, rather than using action?
Also, in using this style of PHP code block I have to call the code below in every single code block, and I'm not sure why? I thought if I put it at the top of my php file, and used require_once that might work but nothing I try works unless I include these in every single code block.
require("config.php");
require("database.php");
Upvotes: 0
Views: 76
Reputation: 522016
No, you cannot call PHP functions from client-side Javascript. First of all, make sure you understand this: What is the difference between client-side and server-side programming?. Having done this, you'll see the only way to execute anything server-side is through an AJAX HTTP call, which is a regular request for a website like any other PHP script would use. HTTP has no concept of "functions" or any particular programming language for that matter. You can request URLs with HTTP, nothing more, nothing less. When these URLs are requested, you can execute PHP code to have these requests handled. Each new request is entirely independent of all other requests, so each one is a standalone script execution which requires its own includes and requires.
Open the network inspector tab in your browser's development tools (Chrome/Safari Web Inspector, Firebug or similar) and watch your AJAX requests go back and forth to the server. This should illustrate the concept a lot better than any explanation would.
Upvotes: 1