Reputation:
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
Upvotes: 1
Views: 1578
Reputation: 4148
Here's the basic idea:
# datastuff.php
// This object will be created upon each request
$MyObject = new MyClass();
$action = (array_key_exists('action', $_GET)) ? $_GET['action'] : '';
switch ($action) {
case 'do_something':
$response = $MyObject->doAfterClick();
// Output relevant feedback to the user or redirect them somewhere based on the response
// This was most likely called via AJAX, so perhaps output JSON data or
// some other means of communicating the response back to the javascript
break;
case 'do_something_else':
// etc...
break;
default:
// Present the information to the user...
break;
}
Your $MyObject
will 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.
Upvotes: 3