23

How to call a PHP class function from an ajax call

animal.php file

class animal
{     
  function getName()
  {
    return "lion";
  }
}

Then in my ajax.php file I have an ajax request, need to get values from getName function

How to do that getName() function can I do like this?

<script type=text/javascript>
  $.ajax({
    type: "POST",
    data: {
      invoiceno:jobid
    },
    url: "animal/getName",
    beforeSend: function() {
    },
    dataType: "html",
    async: false,
    success: function(data) {
      result=data;
    }
  });    
</script>
1
  • What you've started with looks fine, now you just need a page that echoes getName() when the URL animal/getName is requested. Commented Jul 5, 2013 at 12:44

9 Answers 9

45

My answer is the same as Surreal Dreams answer, but with the code.

First. Class animal is OK. Leave it like that:

animal.php

<?php

class animal
{     
  function getName()
  {
    return "lion";
  }
}

Next. Create a new animalHandler.php file.

<?php
require_once 'animal.php';

if(isset( $_POST['invoiceno'] )) {
     $myAnimal = new animal();
     $result = $myAnimal->getName();
     echo $result;
}

Finally. Change your Javascript.

<script type=text/javascript>
  $.ajax({
    type: "POST",
    data: {
      invoiceno:jobid
    },
    url: "animalHandler.php",
    dataType: "html",
    async: false,
    success: function(data) {
      result=data;
    }
  });    
</script>

That's is.

Sign up to request clarification or add additional context in comments.

4 Comments

thanks guys but my problem is if i have to use 50 ajax requests i have to use 50 php files for outputting those results. my doubt is whether i can use all those functions in to a single class called ajax then it will be great for me. but i have been using the same in codeigniter framework. if i can do the same in normal php with classes that would be great. just i want to know if that possible in php.
You can use one ajax.php file to handle all the ajax calls, but beware: It will be big and unmaintenable.
Make a function that works for multiple cases, and use some parameter to access the one you want to retrieve.
It'be so awesome if in jquery 3.4.. it could become like $.post ( ajaxurl, { 'action': 'classname/foomethod', 'data': ... ))
8

You need one additional script, because your animal class can't do anything on its own.

First, in another script file, include animal.php. Then make an object of the animal class - let's call it myAnimal. Then call myAnimal->getName() and echo the results. That will provide the response to your Ajax script.

Use this new script as the target of your Ajax request instead of targeting animal.php.

1 Comment

I was going to answer the same but writing the code. Maybe its more helpful.
2

OOP Currently with php:

ajax.html program(client tier) -> program.php (middle tier) -> class.php (middle tier) -> SQL call or SP (db tier)

OOP Currently with DotNet:

ajax.html program(client tier) -> program.aspx.vb (middle tier) -> class.cls (middle tier) -> SQL call or SP (db tier)

My real-life solution: Do OOA, do not OOP.

So, I have one file per table -as a class- with their proper ajax calls, and select the respective ajax call with a POST parameter (i.e. mode).

/* mytable.php */

<?
session_start();
header("Content-Type: text/html; charset=iso-8859-1");
$cn=mysql_connect ($_server, $_user, $_pass) or die (mysql_error());
mysql_select_db ($_bd);   
mysql_set_charset('utf8');

//add
if($_POST["mode"]=="add")   {
    $cadena="insert into mytable values(NULL,'".$_POST['txtmytablename']."')"; 
    $rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena); 
};

//modify
if($_POST["mode"]=="modify")    {
    $cadena="update mytable set name='".$_POST['txtmytablename']."' where code='".$_POST['txtmytablecode']."'"; 
    $rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena); 
};

//erase
if($_POST["mode"]=="erase") {
    $cadena="delete from mytable where code='".$_POST['txtmytablecode']."'"; 
    $rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena); 
};

// comma delimited file
if($_POST["mode"]=="get")   {
    $rpta="";
    $cadena="select * from mytable where name like '%".$_POST['txtmytablename']."%'"; 
    $rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena); 
    while($row =  mysql_fetch_array($rs)) {
        $rowCount = mysql_num_fields($rs);
        for ($columna = 0; $columna < $rowCount; $columna++)    {
            $rpta.=str_replace($row[$columna],",","").",";
        }
        $rpta.=$row[$columna]."\r\n";
    }
    echo $rpta; 
};

//report
if($_POST["mode"]=="report_a")  {
    $cadena="select * from mytable where name like '%".$_POST['txtmytablename']."%'"; 
    $rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena); 
    while ($row=mysql_fetch_array($rs)) {
        echo $row['code']." ".$row['name']."<br/>"; // colud be a json, html
    };  
};

//json
if($_POST["mode"]=="json_a")    {
    $cadena="select * from mytable where name like '%".$_POST['txtmytablename']."%'"; 
    $rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena); 
    $result = array();
    while ($row=mysql_fetch_array($rs)) {
        array_push($result, array("id"=>$row['code'],"value" => $row['name']));
    };  
    echo json_encode($result);
};
?>

1 Comment

good approach but it will not create its own scope. that's why creating a class is better
1

Can you please mention which are you using any Framework? You method is correct but I want to mention two things over here. First try your URL from the browser and check if its working correctly. Secondly don't use return, in *success: function(data) * data will contain only the output. so use Echo rather then return

Comments

0

For what it is worth, I have used a PHP proxy file that accepts an object as a post -- I will post it here. It works by providing class name, method name, parameters (as an array) and the return type. This is limited as well to only execute classes specified and a limited set of content types to return.

        <?php


    // =======================================================================
        $allowedClasses = array("lnk","objects");    // allowed classes here
    // =======================================================================

    $raw =  file_get_contents("php://input");  // get the complete POST

    if($raw) {

            $data = json_decode($raw);
            if(is_object($data)) {

                $class =   $data->class;        // class:       String - the name of the class (filename must = classname) and file must be in the include path
                $method =  $data->method;       // method:      String - the name of the function within the class (method)
                @$params = $data->params;       // params:      Array  - optional - an array of parameter values in the order the function expects them
                @$type =   $data->returntype;   // returntype:  String - optional - return data type, default: json || values can be: json, text, html

        // set type to json if not specified
                if(!$type) {
                    $type = "json";
                }

        // set params to empty array if not specified
                if(!$params) {
                    $params = array();
                }

        // check that the specified class is in the allowed classes array
                if(!in_array($class,$allowedClasses)) {

                    die("Class " . $class . " is unavailable.");
                }

                $classFile = $class . ".php";

        // check that the classfile exists
                if(stream_resolve_include_path($classFile)) {

                    include $class . ".php";

                } else {

                    die("Class file " . $classFile . " not found.");
                }           

                $v = new $class;


        // check that the function exists within the class
                if(!method_exists($v, $method)) {

                    die("Method " . $method . " not found on class " . $class . ".");
                }

        // execute the function with the provided parameters
                $cl = call_user_func_array(array($v,$method), $params );

        // return the results with the content type based on the $type parameter
                if($type == "json") {
                    header("Content-Type:application/json");
                    echo json_encode($cl);
                    exit();
                }

                if($type == "html") {
                    header("Content-Type:text/html");
                    echo $cl;
                    exit();
                }

                if($type == "text") {
                    header("Content-Type:text/plain");
                    echo $cl;
                    exit();
                }
            }
            else {
                die("Invalid request.");
                exit();
            }       

    } else {

        die("Nothing posted");
        exit();
    }

    ?>

To call this from jQuery you would then do:

            var req = {};
            var params = [];
            params.push("param1");
            params.push("param2");

            req.class="MyClassName";
            req.method = "MyMethodName";
            req.params = params;

                var request = $.ajax({
                  url: "proxy.php",
                  type: "POST",
                  data: JSON.stringify(req),
                  processData: false,
                  dataType: "json"
                });

Comments

0

Try this: Updated Ajax:

$("#submit").on('click', (function(e){

    var postURL = "../Controller/Controller.php?action=create";

    $.ajax({
        type: "POST",
        url: postURL,
        data: $('form#data-form').serialize(),
        success: function(data){
            //
        }
    });
    e.preventDefault();
});

Update Contoller:

<?php

require_once "../Model/Model.php";
require_once "../View/CRUD.php";

class Controller
{

    function create(){
        $nama = $_POST["nama"];
        $msisdn = $_POST["msisdn"];
        $sms = $_POST["sms"];
        insertData($nama, $msisdn, $sms);
    }

}

if(!empty($_POST) && isset($_GET['action']) && $_GET['action'] == ''create) {
    $object = new Controller();
    $object->create();
}

?>

Comments

0

For every ajax request add two data, one is class name and other is function name create php page as follows

 <?php
require_once 'siteController.php';
if(isset($_POST['class']))
{
    $function = $_POST['function'];
    $className = $_POST['class'];
    // echo $function;
    $class = new $className();
    $result = $class->$function();
if(is_array($result))
{
    print_r($result);
}
elseif(is_string($result ) && is_array(json_decode($result , true)))
{
print_r(json_decode($string, true));
}
else
{
echo $result;
}

}
?>

Ajax request is follows

$.ajax({
                        url: './controller/phpProcess.php',
                        type: 'POST',
                        data: {class: 'siteController',function:'clientLogin'},
                        success:function(data){
                            alert(data);
                        }
                    });

Class is follows

class siteController
{     
  function clientLogin()
  {
    return "lion";
  }
}

Comments

0

I think that woud be a sleek workaround to call a static PHP method via AJAX which will also work in larger applications:

ajax_handler.php

<?php

// Include the class you want to call a method from

echo (new ReflectionMethod($_POST["className"], $_POST["methodName"]))->invoke(null, $_POST["parameters"] ? $_POST["parameters"] : null);

some.js

function callPhpMethod(className, methodName, successCallback, parameters = [ ]) {
    $.ajax({
        type: 'POST',
        url: 'ajax_handler.php',
        data: {
            className: className,
            methodName: methodName,
            parameters: parameters
        },
        success: successCallback,
        error: xhr => console.error(xhr.responseText)
    });
}

Greetings ^^

Comments

-1

this is very simple to call the class function using ajax send the class function name along with ajax request.

//ajax code

$.ajax({
url: "ajax.php",
type: "POST",
data: {tid: pId,fun: 'get_hours_by_id'}, //fun key indicate function name
cache: false,
beforeSend: function(){
    $('.btn-disable').prop('disabled', true);
},
error:function(xhr, status, error){                 
    Swal.fire({
        icon: 'error',
        title: 'Error',
        text: error,
    })
    $('.btn-disable').prop('disabled', false);          
},
success: function(response){

}
});

//class ajax code

<?PHP
if (isset($_POST['fun'])) 
{
    $Ajax_Object = new ajax();
    $data = strval($_POST['fun']);
    $result = $Ajax_Object->$data(); //call class function and return result.
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($result);
}
class ajax 
{
    public function get_hours_by_id() 
    {
        $reponse = array(
            'data'  => 0,
            'status' => false,
            'message' => "hello"
        );
        return $reponse;  
    }
}
?>

3 Comments

The example code does what is needed but is a little bit complex example from the questioner perspective. The answer could be better if it include similar classes and naming than in the original question. Also, dynamic function call is used that is not so clear way to present minimum need.
The example code does what is needed but is a little bit complex example from the questioner perspective. The answer could be better if it include similar classes and naming than in the original question. Also, dynamic function call is used that is not so clear way to present minimum need.
Hi @T.Nylun, thank you for your feedback. I am facing this issue in my project. then I will solve this issue in the above code. this is my project code.so I put all code here for better understanding.

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.