1

index.php

<?php
include ('db.php');  // db connections
include ('functions.php');  //  I need some functions
?>

The same php functions I need via jquery.ajax call.

$.post('functions.php', {vars}, function(data) {
    console.log(data);
});

I'm getting error - $db is not defined because $db.php is not included in functions.php;

If I include db.php inside functions.php I'm getting error inside index.php - $db is already declared.

for now I repeat the same functions inside functions.php and an another file with db.php included, and I call it with ajax, but hope there is a more clever solution.

11
  • 1
    Include your db inside your functions.php, and only inside your functions.php. Use require_once on both includes, so it will always load only once. Commented Sep 20, 2018 at 18:11
  • 3
    It seems odd that you would be requesting functions.php directly via ajax. Wouldn't that file only contain function definitions and not any directly-executed code? Commented Sep 20, 2018 at 18:12
  • you should use namespace to avoid collision of names Commented Sep 20, 2018 at 18:15
  • @PatrickQ, functions.php gets some data from database, proccessed via js Is that odd?. Commented Sep 20, 2018 at 18:16
  • 1
    @aynber, do you mean include db inside functions and functions inside index with require_once? Commented Sep 20, 2018 at 18:19

1 Answer 1

1

You should use require_once at first of of your files, if a file already loaded so the require_once not load it again.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.