GregHBushnell GregHBushnell - 1 year ago 31
Ajax Question

calling php functions with ajax instead of php files

Is it standard practice to be creating lots of separate .php files when using ajax? or is there a way to call certain functions with relative ease?

for example, for my checkusername code I have to create a separate php file that does this"GET", "CheckUsername.php?q="+name, true);

and now if I was to go and create a bunch of ajax calls I will need lots of separate .php files. is there an easy way to group these up? whether it be in functions or even a folder that I can put them all in?

Answer Source

If using an MVC framework, you will typically be able to route all ajax requests to one Controller file, and call different methods for each different ajax call.

If you don't want to use an MVC, you can make a pseudo-router in 1 file by passing a query parameter (via your ajax request) which distinguishes functions, using variable variables. For example, if your backend file looks like this:


    $function_id = $_GET['function_id'];// this acts as a low level but functional router

    function func1() {}

    function func2() {}

    echo $function_id();


You can add query parameters like so:

var func = 'func1';"GET", "CheckUsername.php?q="+name+"&function_id="+func, true);

The return value will be from function func1() in this case. $_GET has global scope, so no need to pass it as an argument to the functions in your backend file.