4

I realize that calling database from JavaScript file is not a good way. So I have two files:

  1. client.js
  2. server.php

server.php has multiple functions. Depending upon a condition, I want to call different functions of server.php. I know how to call server.php, but how do I call different functions in that file?

My current code looks like this:

 function getphp () {
     //document.write("test");
     xmlhttp = new XMLHttpRequest();
     xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            // data is received. Do whatever.
        }
     }
     xmlhttp.open("GET","server.php?",true);
     xmlhttp.send();
 };

What I want to do is something like (just pseudo-code. I need actual syntax):

xmlhttp.open("GET","server.php?functionA?params",true);
2
  • Just use a micro-framework or a full flegdeg one Commented Oct 3, 2014 at 7:26
  • @Cerbrus: I believe this is not a duplicate. The link you suggested tell me how to call one particular php file. I am looking to find how to call multiple functions all in one php file. Commented Oct 3, 2014 at 7:33

5 Answers 5

5

Well based on that premise you could devise something like this:

On a sample request like this:

xmlhttp.open("GET","server.php?action=save",true);

Then in PHP:

if(isset($_GET['action'])) {
    $action = $_GET['action'];

    switch($action) {
        case 'save':
            saveSomething();
        break;
        case 'get':
            getSomething();
        break;

        default:
            // i do not know what that request is, throw an exception, can also be
        break;
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

Add a default case to the switch statement, which throws an exception, for easy debugging.
So there is no built-in way to do this?
This is the built-in way.
@ManasPaldhe what does that mean? built-in way? so you want a function that does this all? no i don't think there is no function that does it all.
@Ghost: Yes, that is what I meant. That is fine. I will use the above answer! :)
|
1

Just do something like this, i hope this will work

xmlhttp.open("GET","server.php?function=functioName&paramsA=val1&param2=val2",true);

Comments

1

You will most likely need to create the mechanism yourself.

Say the URL will look like server.php?function=foo&param=value1&param=value2

On the server side you will now have to check whether a function with such a name exists, and if it does, call it with these parameters. Useful links on how to do it are http://php.net/manual/en/function.function-exists.php and http://php.net/manual/en/functions.variable-functions.php

Otherwise, if you don't want to have it like this, you can always go with if/switch and simply check that if $_GET["function"] is something, then call something etc.

Comments

1

You can use jQuery too. Much less code than pure js. I know pure js is faster but jQuery is simpler. In jQuery you can use the $.ajax() to send your request. It takes a json structured array like this:

$.ajax({
    url: "example.php",
    type: "POST",
    data: some_var,
    success: do_stuff_if_no_error_occurs(),
    error: do_stuff_when_error_occurs()
});

Comments

1

Here's a dynamic way to solve this issue:

xmlhttp.open("GET","server.php?action=save",true);

PHP Code:

<?php
$action = isset($_GET['action']) ? $_GET['action'] : ''; 
if(!empty($action)){
    // Check if it's a function
    if(function_exists($action)){
        // Get all the other $_GET parameters
        $params = array();
        if(isset($_GET) && sizeof($_GET) > 1){
            foreach($_GET as $key => $value){
                if($key != 'action'){
                    $params[] = $value;
                }
            }
        }
        call_user_func($action, $params);
    }
}
?>

Keep in mind that you should send the parameters in the same order of function arguments. Let's say:

xmlhttp.open("GET","server.php?action=save&username=test&password=mypass&product_id=12",true);

<?php
function save($username, $password, $product_id){
   ...
}
?>

You can't write the API Call that way:

xmlhttp.open("GET","server.php?action=save&password=mypass&username=test&product_id=12",true);

Keep in mind that it's really bad to send "function namespaces" along with the parameters to a back-end. You're exposing your back-end and without proper security measures, your website will be vulnerable against SQL Injection, dictionary attack, brute force attack (because you're not checking a hash or something), and it'll be accessible by almost anyone (you're using GET using of POST and anyone can do a dictionary attack to try to access several functions ... there's no privileges check) etc.

My recommendation is that you should use a stable PHP Framework like Yii Framework, or anything else. Also avoid using GET when you're sending data to the back-end. Use POST instead.

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.