Click here to Skip to main content
16,004,505 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi
I have a php function and i need to call it from from jquery ajax to populate my datatable.

What I have tried:

my php file
PHP
public static function getEmployeesList() {
      $list = [];
      $dbConn = Connection::getInstance();
      $req = $dbConn->query('SELECT firstname,lastname,phone,email FROM employee');

      // we create a list of Post objects from the database results
      foreach($req->fetchAll() as $post) {
        $EmployeesList[] = new Post($post['firstname'], $post['lastname'], $post['phone'],$post['email']);
      }

      return $EmployeesList;
    }



jquery below

JavaScript
tblEmployees = $('#tblEmployees').dataTable({
        "oLanguage": { "sEmptyTable": "No data to display" },
        "bJQueryUI": false,
        "bAutoWidth": false,
        "sPaginationType": "full_numbers",
        "sAjaxSource": '../EmployeeService.php?method=getEmployeesList()',//problem is here.
Posted
Updated 9-Mar-16 0:58am

1 solution

Using plain PHP, you cannot call a PHP function directly, instead you send your request to a php script and pass it a parameter based on which then call the function that you want to invoke. For example:
in AJAX:
JavaScript
$.ajax({ url: 'phpscriptname.php',
         data: {function2call: 'getEmployeesList', otherkey:otherdata},
         type: 'post',
         success: function(output) {
                      alert(output);
         }
});

in phpscriptname.php:
C#
if(isset($_POST['function2call']) && !empty($_POST['function2call'])) {
    $function2call = $_POST['function2call'];
    switch($function2call) {
        case 'getEmployeesList' : getEmployeesList();break;
        case 'other' : // do something;break;
        // other cases
    }
}
 
Share this answer
 
Comments
Anele Ngqandu 10-Mar-16 3:28am    
Hi, not sure if am allowed to place some code here but..
query('SELECT firstname,lastname,phone,email FROM employee');

// we create a list of Post objects from the database results
foreach($req->fetchAll() as $post) {
$EmployeesList[] = new Employee( $post['firstname'], $post['lastname'], $post['phone'],$post['email']);

return json_encode($EmployeesList);

}
}

this my php file...

$.ajax({
url: '/EmployeeService.php',
data: { getEmployees: 'getEmployees' },
type: 'post',
success: function (output) {
alert(output);
}
});

jquery file...

I get an error that my EmployeeService.php is not found, what am i missing ??

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900