I need some help with this please
I can't get a handle on it.
The problem is that I want to call a class method, in this case with static methods with an ajax call.
I have put the helper class in the same folder as the script that is called by ajax for easy referencing and try to include it.
Could it be that my refencing is wrong?
If I make a testclass in the file that is called by ajax I can get a response.
class test {
public function testit() {
return "testit";
}
}
$t=new test;
$check= $t->testit();
switch($action) {
case "someaction":
$data = array();
$file='input_helper.php';
include_once $file;
$check= input_helper::ip_address();
header('Content-type: application/json');
$output = array(
"check" => $check,
"user" => $data
);
echo json_encode($output);
exit(0); // Stop script.
break;
//...
EDIT FOR MORE CLARIFICATION
The action is set as a post variable in the ajax function
The ajax url points to a script that takes some action based on the posted variables
thanks, Richard
<?php
include_once 'your/class/path/helper_class.php';
.
.
at the top of your PHP page should do it. it really has nothing to do with AJAX. If your PHP file is in fact being hit on the callback, then that should work properly.
Optionally, to test that your path is correct, if you do:
<?php
require 'your/class/path/helper_class.php';
.
.
If the path is not correct PHP will throw a fatal E_ERROR level error.
Related
I have a class with this function:
public function loadTemplate($template)
{
return require "templates/$template.php";
}
It's fine, but I have a problem with it.
Let's say I have this code:
require('class.php');
$class = new ClassName; // ClassName is the class which contains the function loadTemplate()
$name = 'Jerry';
$class->loadTemplate('myname');
And "myname.php" is:
<?php
echo "My name is $name.";
In this case I get an error because "myname.php" is actually included in the file of the class and so $name is undefined.
How do I overcome this problem?
Not discussing whether that's the best design, here's how you can do it.
public function loadTemplate($template, $vars)
{
extract($vars);
ob_start();
require "templates/$template.php";
$viewContent = ob_get_contents();
ob_get_clean();
return $viewContent;
}
Pass your variables as an associative array:
$vars = ['name' => 'Jerry']
And then output it:
echo $class->loadTemplate('myname', $vars);
What this does is, it creates variables from the array and loads the view, but with the "ob_" functions we are capturing the output buffer and then echoing it if we want.
You could probably get away without using ob_ just by echoing the require method as you were trying. I'd say give it a go and use what you prefer.
I have just created a class to control my php application, and I have one big problem ( I use 2 days for thinking and searching about it but can't find any solutions). My class contains a method named register(), which load scripts into pages. My class is:
class Apps
{
protected $_remember; // remember something
public function register($appName)
{
include "$appName.php"; //include this php script into other pages
}
public function set($value)
{
$this->_remember = $value; // try to save something
}
public function watch()
{
return $this->_remember; // return what I saved
}
}
And in time.php file
$time = 'haha';
$apps->set($time);
As the title of my question , when I purely include time.php into main.php, I can use $apps->set($time) ($apps has been defined in main.php). Like this main.php:
$apps = new Apps();// create Apps object
include "time.php";
echo $apps->watch(); // **this successfully outputs 'haha'**
But when I call method register() from Apps class to include time.php , I got errors undefined variable $apps and call set method from none object for time.php (sounds like it doesn't accept $apps inside time.php to me) . My main.php is:
$apps = new Apps();// create Apps object
$apps->register('time'); // this simply include time.php into page and it has
//included but time.php doesn't accept $apps from main.php
echo $apps->watch(); // **this outputs errors as I said**
By the way , I'm not good at writing . So if you don't understand anything just ask me. I appreciate any replies. :D
If you want your second code snippet to work, replace the content of time.php with:
$time = 'haha';
$this->set($time); // instead of $apps->set($time);
since this code is included by an instance method of the Apps class, it will have access to the instance itself, $this.
I am using xmlprc server in codeignter for web services . the flow of my application is that i need to pass parameters to the xmlrpc server method which then should invoke another controller class method which would set the parameters in a js function and that js method is invoked concurrently .
The problem i am facing is in calling the controller class method from the xmlrpc server method and getting the response to the server parent method which could then be fetched using xmlhttprequest.
my xmlrpc server method is:
function update_p($request) {
$parameters = $request->output_parameters();
$this->session->set_userdata(array("portfolio" =>$parameters['0']["portfolio"]));
$this->session->set_userdata(array("filter" =>$parameters['0']["filter"]));
$url = base_url("ControllerClass/update_p?".$parameters['0']["portfolio"].'&'.$parameters['0']["filter"]);
header("Location: $url");
$xml_rpc_rows=array("portfolio"=>$parameters['0']["portfolio"],"filter"=>$parameters['0']["filter"]);
$response = array(
$xml_rpc_rows,
'struct');
$this->xmlrpc->send_response($response);
}
Controller Class method:
public function update_p() {
$loginid = $this->session->userdata('loginid');
if(!isset($loginid)){
die;
}
error_reporting(E_ERROR);
if (time()>$this->session->userdata('expire')) { redirect("/dashboard/logout?expired=Y","location",401); die; }
$out='';
$request="USER ".$loginid.($this->session->userdata('isMobile')?"#mobile":"")."\n";
if(isset($_GET["portfolio"])) {
$portfolio=trim($_GET["portfolio"]);
$request.='ECHO "LISTP":'."\nLISTP0 #".$portfolio;
if(isset($_GET["filter"])) {
$filter=trim($_GET["filter"]);
$request.=" -".$filter;
}
if(isset($_GET["sort"])) {
$sort=trim($_GET["sort"]);
if ($sort>=1024) $request.=" -s".($sort&1023);
else $request.=" -S".$sort;
}
$ph = isset($_GET["first"]);
if ($ph) {
$this->load->model('Model');
$resultArray = $this->Model->getData($this->session->userdata('loginid'),$this->session->userdata('isMobile')?'mobile':'default','listp');
$request.=" ".$resultArray[0]['listp'];
}
$request.="\nECHO ,\n";
if(isset($_GET["watch"])) {
$portfolio=trim($_GET["watch"]);
if ($ph)
$resultArray = $this->Model->getData($this->session->userdata('loginid'),$this->session->userdata('isMobile')?'mobile':'default','watch');
$request.='ECHO "watchl":'."\nLISTP1 #".$portfolio." -WL ".($ph?$resultArray[0]['watch']:"")."\n";
$request.='ECHO ,"watchs":'."\nLISTP1 #".$portfolio." -WS\nECHO ,\n";
}
}
$request.="RISk\nECHO ,\nPnL\n";
if ($result=$this->getData($request."BYE\n")) {
if (result!='') $out=$result."\n";
}
ob_start('ob_gzhandler');
echo "{".$out."}";
ob_end_flush();
}
I can not figure out how to get the controller method result in the server method anyone who can shed some light on this would be much appreciated .
Thankyou.
Your controller method is expecting to output the result as an echo statement, which goes to the browser, rather than to return it in a variable. This means your server function is having to try to capture the output of that controller method. That setup is much more awkward and prone to error.
Unless you also need to access your update_p method directly from a browser you should change your Controller to simply return the output which really means this controller is more of a library and should probably go in the libraries folder. You will need to change your controller code a bit so that instead of grabbing the parameters from $_GET you are getting them as arguments, which in CodeIgniter is what you should be doing anyway.
So from the end of update_p just do this instead of your echo:
return "{".$out."}";
Then in your xmlrpc server do this:
$controller = new ControllerClass();
$result = $controller->update_p($parameters['0']["portfolio"], $parameters['0']["filter"]);
Then do whatever you want with your $result.
newbie in PHP here, sorry for troubling you.
I want to ask something, if I want to include a php page, can I use parameter to define the page which I'll be calling?
Let's say I have to include a title part in my template page. Every page has different title which will be represented as an image. So,
is it possible for me to call something <?php #include('title.php',<image title>); ?> inside my template.php?
so the include will return title page with specific image to represent the title.
thank you guys.
An included page will see all the variables for the current scope.
$title = 'image title';
include('title.php');
Then in your title.php file that variable is there.
echo '<h1>'.$title.'</h1>';
It's recommended to check if the variable isset() before using it. Like this.
if(isset($title))
{
echo '<h1>'.$title.'</h1>';
}
else
{
// handle an error
}
EDIT:
Alternatively, if you want to use a function call approach. It's best to make the function specific to activity being performed by the included file.
function do_title($title)
{
include('title.php'); // note: $title will be a local variable
}
Not sure if this is what you're looking for, but you can create a function to include the file and pass a variable.
function includeFile($file, $param) {
echo $param;
include_once($file);
}
includeFile('title.php', "title");
In your included file, you could do this:
<?php
return function($title) {
do_title_things($title);
do_other_things();
};
function do_title_things($title) {
// ...
}
function do_other_things() {
// ...
}
Then, you could pass the parameter as such:
$callback = include('myfile.php');
$callback('new title');
Another more commonly used pattern is to make a new scope for variables to be passed in:
function include_with_vars($file, $params) {
extract($params);
include($file);
}
include_with_vars('myfile.php', array(
'title' => 'my title'
));
The included page will already have access to those variables defined prior to the include. If you require include specific variables, I suggest defining those variables on the page to be included
I am trying to use AMF PHP to pass variables to a flash file, thus far I cannot see anything wrong with my code, but I have very little experience with creating classes, so here it goes, here is my code,
index.php:
<?php
include "amfphp/services/flashMe.php";
$session = true;
if ($session == true) {
$uid = '12345';
$thing = new flashMe;
$thing->push($uid);
} else {
//login
}
?>
flashMe.php:
<?php
class flashMe {
public function __construct() {
}
public function push($one)
{
return $one;//sends the uid to the flash file?
}
}
?>
Flash is looking for the flashMe class and the push method within that class, but I keep getting null variables in my flash file when I run it, is there something wrong with this code?
Thanx in advance!
Your index.php file is unnecessary.
Your second file is incomplete. Here is the example from the docs for their "hello world" class file:
<?php
class HelloWorld
{
function HelloWorld()
{
$this->methodTable = array
(
"say" => array
(
"access" => "remote",
"description" => "Pings back a message"
)
);
}
function say($sMessage)
{
return 'You said: ' . $sMessage;
}
}
?>
This file should be saved as "HelloWorld" matching the "class HelloWorld" you have named in the php file (you did this part right with FlashMe).
The example file in the docs for the Flash piece (in actionscript) is here:
import mx.remoting.*;
import mx.rpc.*;
import mx.remoting.debug.NetDebug;
var gatewayUrl:String = "http://localhost/flashservices/gateway.php"
NetDebug.initialize();
var _service:Service = new Service(gatewayUrl, null, 'HelloWorld', null , null);
var pc:PendingCall = _service.say("Hello world!");
pc.responder = new RelayResponder(this, "handleResult", "handleError");
function handleResult(re:ResultEvent)
{
trace('The result is: ' + re.result);
}
function handleError(fe:FaultEvent)
{
trace('There has been an error');
}
The gateway URL should go to wherever your services can be reached. I'm sure if you try a few you'll find the right one. The neat thing about amfphp is that it allows you to also test your services out before you try implementing them in the gateway (if you go to the URL in your browser).
I'm pretty new to AMFPHP as well, but I've found the docs to be extraordinarily useful. If you need more help on classes, you can find more info on the PHP docs page.
You missed the parenthesis after new flashMe
$thing = new flashMe();
$thing->push($uid);
Amfphp or Zend AMF only allow you to call public methods on a remote class that is exposed by your gateway. You example is not a class and therefore no remote method can be called. This looks more like something that you would do with an http post.
http://framework.zend.com/manual/en/zend.amf.server.html