Search code examples
javascriptphpjqueryajaxcall

AJAX connect to PHP OOP WebService


Why does this not work?

class WebService {
    public static function CheckUserLogin() {
    }
}

How i can call this function?

My login.php Form

<form id="form" name="form" method="POST" onsubmit="" action="">

E-Mail: <input type="text" size="30" name="email" id="email" >
Passwort: <input type="text" size="30" name="passwort" id="passwort" >

<input type="submit" value="Login" name="submit" />

</form>

login.js

 $(function () {
    $('form').on('submit', function (e) {
        var email = document.getElementById('email').value;
        var passwort = document.getElementById('passwort').value;

        $.ajax({
            type: "POST",
            url: "WebService.php",
            data: "{ 'email': '" + email + "', passwort: '" + passwort + "' }",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                alert(response);
            },
            failure: function (response) {
                alert(response);
            }
        });
      e.preventDefault();
    });
  });

I want to Call the Function CheckUserLogin(). How i can do this? Or what i must do?

Thank you very much!


Solution

  • In your ajax call, alongwith the url you can send a parameter, say- action:

    ....
    url: "WebService.php?action=checkLogin",
    ....
    

    Then in PHP, just get this variable and call the desired function-

    if(isset($_GET['type'])){
       if($_GET['type'] == "checkLogin"){
          $ws = new WebService;
          echo $ws->CheckUserLogin(); 
          // this will call the desired function and the result will be obtained by the ajax
       }
    }
    

    Similarly you can use the same concept to call different functions at different points.