0

I'm quite a beginner with AJAX, so references are welcome.

Is it possible to call for a specific PHP function from a PHP file (and not run the whole PHP file) with AJAX? If so, how?

Background: I have a button that I want with jQuery that onclick on it, a specific PHP function from some given PHP file would be called. I prefer to not create a whole new file to run the body of the function, because the PHP file that I want to run the code from is a big functionality file (a WordPress functions.php file).

  • what do you mean by "run the whole PHP file" ? often the file is already loaded and then you can call a function defined in this file. then it's not the whole file which is run only the function. – mmm Oct 7 '17 at 21:24
  • using AJAX you are calling the function from within a theme, i mean its a button in another website, or in the same website? – David Lee Oct 8 '17 at 0:25
-1

No, it's not possible if you want to follow the best practice, and neither you need and should do it.

When you make an AJAX call, some parts or WordPress's core will be loaded based on the AJAX type (whether it's admin-Ajax or REST-API). It is vital for this to happen, since some scripts demand on using core functions such as get_the_ID().

Your theme's functions.php file is going to be loaded in this process. If your file runs some functions by itself, then you probably have to optimize your functions.php, since this should not usually happen, and the functions should be run only when necessary.

  • Thanks for the explanations. :) Follow-up question: how could I make a request, then? Create a separate PHP with the function and call that file with AJAX? – Gal Grünfeld Oct 8 '17 at 1:47
  • If you are referring to directly calling a PHP file using AJAX, that would be a security issue. – Jack Johansson Oct 8 '17 at 13:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.