Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call different PHP functions from javascript

Tags:

javascript

php

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);
like image 702
Manas Paldhe Avatar asked Jan 09 '23 16:01

Manas Paldhe


1 Answers

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;
    }
}
like image 138
Kevin Avatar answered Jan 12 '23 09:01

Kevin