I'm writing a function that will return database results.
I need it to return
the data if the function is called from another function and echo
the data when its called via AJAX.
Possible Solutions
- Pass in a parameter...
if($echo) echo $data; else return $data;
- Separate functions...
function employees_ajax() { echo $this->employees(); }
I'd prefer something smarter that can detect that 'itself' was called from another function and return
instead of echo
.
UPDATE
Another possibility would be to check the $_SERVER variable.
"As far as I know, the X-Requested-With is sent by the Ajax functions of most major Frameworks but not all...it's safe to say it's not generally a 100% reliable method to determine whether a request is an AJAX request or not."
Does $_SERVER['HTTP_X_REQUESTED_WITH'] exist in PHP or not?
It would be fail-safe to rely on the server rather than the client / js framework.
UPDATE 2: RESULT
function employees($id = NULL, $return = FALSE) {
.
.
.
if($return === TRUE) return json_encode($data);
else echo json_encode($data);
}