Razvan Razvan - 5 days ago 5
Ajax Question

Ajax call method from class php

Hi ,

I want to call a method from a class through ajax.
The class is something like this :

class MyClass{
public function myMethod($someParameter,$someParameter2){
//do something
return $something;
}
private function myMethod2($someParameter3){
//do something
return something;
}

}


Can i use ajax to call a class method (myMetod(2,3)) and with the return to do someting?
Can i use it like this?

$.ajax({
url : 'myClass.php',
data : {
someData: '2,3',
}
type : 'POST' ,
success : function(output){
alert(output)
}
});

Answer

You need to create php script that calls this class method and can be called as ajax request. Create a file like:

For Example:

myfile.php

<?php

   $date = $_POST; // print_r( $_POST ); to check the data

   $obj = new MyClass();

   $obj->myMethod( $_POST['field1'], $_POST['field2'] );
   $obj->myMethod2( $_POST['field1'] );

?>

And change your jQuery code to:

$.ajax({
        url  : 'path/to/myfile.php',
        data : { someData: '2,3' },
        type : 'POST' ,
        success : function( output ) {
                    alert(output)
                  }
});
Comments