Search code examples
phpajaxnamespacesmedoo

How to call medoo 1.5 inside a function with ajax?


First question here. I want to call a php function with ajax. Inside the function I have a class from a library that is on a namespace.

I've been using medoo with version 0.9 inside functions in php and everything is working great. I also use the same functions with ajax calls.

In my function.php file I have:

//if called from js with ajax I use a var in the link to know for ex. variable_from_js=1
if(isset($_GET['variable_from_js']){
  $response = my_function();
  echo $response;//i catch the response with js then
  exit;
}

//my function
function my_function(){
 $a = new Medoo(DB_NAME);//DB_NAME is a global
 ...
}

Medoo is using namespaces in versions > 1.2 and so many other libraries out there. When I call my_function() directly i use:

require 'Medoo.php';
require 'function.php';
use Medoo\Medoo;
echo my_function();

and everything works great. Now if I call the same ajax call I get interanl server error because the class Medoo is not found.

I cannot use the code:

use Medoo\Medoo;

inside the if statement or inside the function because of the local scope of these things. I should call it on the global scope. But I am using ajax calls.

Should I write "use" statement again inside function.php or should I do it elsewhere? Is there a solution or the only solution is to get rid of "use" statement and go with the full namespace path when calling the class (inside function)?


Solution

  • You should only call Medoo once in your code, so at the top of your php file

    require 'Medoo.php';
    require 'function.php';
    use Medoo\Medoo;
    $db = new Medoo(DB_NAME);
    

    and then pass the medoo class to your function such as

    echo my_function($db);
    

    In your function, you could then use medoo such as

    function my_function($db){
        $value = $db->get('...','...','...');
        return $value;
    }
    

    hope this helps.