I have a PHP file, …/datastuff.php
On this page a PHP object is instantiated. (The class is written in another file).
public class MyClass{
//....
public function doAfterClick(){
//.....
}
}
So in datastuff.php I do
$MyObject = new MyClass();
//user specific data is added to $MyObject
Now I want to call $MyObject->doAfterClick(), when the user presses a button on datastuff.php
I think AJAX is the general solution for this type of problem. But I am not sure how to do this?
If I wanted to call a PHP function written on another page I could use AJAX to POST data to that page. But I want to stay on this page, because MyObject needs to call the method.
If I POST back to datastuff.php won’t $MyObject be lost?
If I make it a Singleton or Global would this then work?
I looked at this, which is a similar problem, ut is not quite what I am looking for:
Using JQuery ajax to call a PHP file, process, but stay on same page
Here’s the basic idea:
Your
$MyObjectwill be created upon each request (i.e. on initial page load and after the button is clicked and fires an AJAX request) but it may be identical in each request assuming it has been given the same data. After the button is clicked, an ajax request to “datastuff.php?action=do_something” will make sure the relevant method is called.Although something like this would work, it is not good code design. I’d recommend you spend some time researching MVC (Model, View, Controller) patterns.