1

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

xhttp.open("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?

4
  • Look into any frameworks: yii, lumen, laravel, silex and so on. They group request into several classes. Commented Sep 20, 2016 at 19:59
  • 1
    There are many possible answers to this. You can, of course, group files by folders. You can create a service which accepts different endpoints MyService.php/CheckUsername etc. I'm sure there are many other solutions, however, your question is rather vague. Commented Sep 20, 2016 at 20:00
  • Please see my answer on this other question and contemplate the possible security risks. Commented Sep 20, 2016 at 21:00
  • at Server side you can make this conditional. if(queryString = true) then ..else.. Just use query string. .load() jQuery will works well to load the page using Query String Commented Sep 21, 2016 at 3:39

1 Answer 1

0

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:

<?php 

    $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';

xhttp.open("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.

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.