Page 1 of 1

Call an instantiated class's function from javascript

Posted: Thu Jan 28, 2016 2:19 pm
by imaxeman69
First some background and please let me know if what I'm doing is not on the right track.

I have a php page that has a form that accepts some input.

I also have a PHP class that basically does a bunch of queries that I instantiate at the top of the form.

When an event happens, say an input box's onChange event, I'd like to call a function in the instance of my PHP class that, say returns an array, that I can manipulate with Javascript.

I realize that this is going to be some sort of AJAX call, but I can't seem to figure out how to access the instance of my class's functions.

Hope this makes sense.

Thanks in advance.

Re: Call an instantiated class's function from javascript

Posted: Thu Jan 28, 2016 2:38 pm
by Celauran
Sounds like you want to expose a public API, call its endpoints over AJAX, and instantiate your object based on parameters sent to the endpoint.

Re: Call an instantiated class's function from javascript

Posted: Thu Jan 28, 2016 11:18 pm
by Christopher
imaxeman69 wrote:I realize that this is going to be some sort of AJAX call, but I can't seem to figure out how to access the instance of my class's functions.
Well ... whatever PHP script is being called will instantiate you class, call the requested method (with any parameters passed) which will return an array, convert the array to JSON and finally echo the JSON as the response. The Ajax call receives the JSON, converts it into an array and accesses the data.

The PHP script called depends on your architecture. It could just be mypage.php, or if you are using a MVC framework it would be an Action method in a Controller dispatched by a Front Controller.