I need to fire a php class from a javascript function.
code:
<input type="button" name="Submit" value="Submit" class="opinionbox"
onclick="verifyControl('<?=$control_no?>')"/>
function verifyControl(rNo) {
Cont_no=document.getElementById("ContNo").value;
if(rNo==Cont_no) {
frames['frame1'].print();
showPage('payment');
}
else if(rNo!=Cont_no) {
alert("invalid control no");
}
}
i need to run the code
$data = $obj_com -> getSelectedData('tbl',
'control_no', $contno);
$control_no = $contno;
$obj_com -> recordPay('tbl',$contno);
inside the verifyControl() how can I do this?
You cannot "call" a PHP class from Javascript because Javascript is run on the client side (ie, the browser) while PHP is run on the server. What you can do, however, is call a PHP script asynchronously, get its output, and do fun stuff with javascript. This is known as AJAX. If you're going to go down this road, you are highly advised to use a library like jQuery and learn from there. Here are a few questions to get you started (check out the answers):
How to dynamically call a php function in javascript
Javascript and PHP functions
To call PHP code from Javascript, given that PHP is executing on the server and Javascript is executing on the client, you will need to set up some sort of interface at the server that can be accessed remotely.
You may also want to be aware of the security implications of doing so. In particular, if you want to ensure that only your users will be calling your server in this way - that is, if a malicious user calling this code could do damage, you will need some sort of authentication.
You will also need to decide on a protocol for communicating between the client and server.
Protocols such as SOAP and XML-RPC define everything you need to remotely call procedures on the server. Or you can roll your own, just by calling a certain URL and receiving a certain result, in a certain format (JSON can help) from the server.
you can use Brent Ashley jsrsClient.js or $.ajax of jQuery Javascript lib.
Related
The actual questions
How to "map" access restrictions so it can be used from php and javasript?
What kind of method should I use to share access restrictions / rules between php and javascript?
Explanation
I have created a RESTful backend using php which will use context-aware access control to limit data access and modification. For example, person can modify address information that belongs to him and can view (but not modify) address information of all other persons who are in the same groups. And of course, group admin can modify address details of all the persons in that group.
Now, php side is quite "simple" as that is all just a bunch of checks. Javascript side is also quite "simple" as that as well is just a bunch of checks. The real issue here is how to make those checks come from the same place?
Javascript uses checks to show/hide edit/save buttons.
PHP uses checks to make the actual changes.
and yes,
I know this would be much more simpler situation if I ran javascript (NodeJS or the like) on server, but the backend has already been made and changing ways at this point would cause major setbacks.
Maybe someone has already deviced a method to model access checks in "passive" way, then just use some sort of "compiler" to run the actual checks?
Edit:
Im case it helps to mention, the front-end (js) part is built with AngularJS...
Edit2
This is some pseudo-code to clarify what I think I am searching for, but am not at all certain that this is possible in large scale. On the plus side, all access restrictions would be in single place and easy to amend if needed. On the darkside, I would have to write AccessCheck and canAct functions in both languages, or come up with a way to JIT compile some pseudo code to javascript and php :)
AccessRestrictions = {
Address: {
View: [
OWNER, MEMBER_OF_OWNER_PRIMARY_GROUP
],
Edit: [
OWNER, ADMIN_OF_OWNER_PRIMARY_GROUP
]
}
}
AccessCheck = {
OWNER: function(Owner) {
return Session.Person.Id == Owner.Id;
},
MEMBER_OF_OWNER_PRIMARY_GROUP: function(Owner) {
return Session.Person.inGroup(Owner.PrimaryGroup)
}
}
canAct('Owner', 'Address', 'View') {
var result;
AccessRestrictions.Address.View.map(function(role) {
return AccessCheck[role](Owner);
});
}
First things first.
You can't "run JavaScript on the server" because Javascript is always run on the client, at the same way PHP is always run on the server and never on the client.
Next, here's my idea.
Define a small library of functions you need to perform the checks. This can be as simple as a single function that returns a boolean or whatever format for your permissions. Make sure that the returned value is meaningful for both PHP and Javascript (this means, return JSON strings more often than not)
In your main PHP scripts, include the library when you need to check permissions and use the function(s) you defined to determine if the user is allowed.
Your front-end is the one that requires the most updates: when you need to determine user's permission, fire an AJAX request to your server (you may need to write a new script similar to #2 to handle AJAX requests if your current script isn't flexible enough) which will simply reuse your permissions library. Since the return values are in a format that's easily readable to JavaScript, when you get the response you'll be able to check what to show to the user
There are some solutions to this problem. I assume you store session variables, like the name of the authorized user in the PHP's session. Let's assume all you need to share is the $authenticated_user variable. I assume i'ts just a string, but it can also be an array with permissions etc.
If the $authenticated_user is known before loading the AngularJS app you may prepare a small PHP file whish mimics a JS file like this:
config.js.php:
<?php
session_start();
$authenticated_user = $_SESSION['authenticated_user'];
echo "var authenticated_user = '$authenticated_user';";
?>
If you include it in the header of your application it will tell you who is logged in on the server side. The client side will just see this JS code:
var authenticated_user = 'johndoe';
You may also load this file with ajax, or even better JSONP if you wrap it in a function:
<?php
session_start();
$authenticated_user = $_SESSION['authenticated_user'];
echo <<<EOD;
function set_authenticated_user() {
window.authenticated_user = '$authenticated_user';
}
EOD;
?>
is it possible to run some javascript expression? for example echo eval("Math.sqrt('25')");
In normal situations :
PHP runs on the server
and, then, Javascript is run on the client, in the browser.
So, no, it's not quite possible to have PHP execute some Javascript code on the server.
But there is at least on PHP extension that embed (or wrap arround) a Javascript engine, and, as a consequence, allows one to execute Javascript on the server, from PHP.
The extension I'm thinking about is the spidermonkey one : installing and enabling it on your server will allow you to execute Javascript code, on the server, from PHP.
Of course, like any other PHP extension, you'll need to be admin of your server, in order to install it -- and this one is never installed by default, as it answers a very specific need.
About this extension, I have never seen it used in real situations, and there are not many people who tried it... here are two articles you might want to read :
Using JavaScript in PHP with PECL and SpiderMonkey
and SpiderMonkey : Exécuter du Javascript côté serveur, depuis PHP (this one is in french, and on my own blog)
Try this
echo "<script language='javascript'> Math.sqrt('25') </script>"
There is also the J4P5
I don't know if it's still maintained but you can always fork it, it's released under the GPL license.
put your php into a hidden div and than call it with javascript
html / php part
<div id="mybox" style="visibility:hidden;"> echo sqrt(25); </div>
javascript part
var myfield = document.getElementById("mybox");
myfield.visibility = 'visible';
now, you can do anything with myfield... like this
alert(myfield);
Since PHP is a server-side scripting language that runs on the server and Javascript is a client-side scripting language that runs in a browser you would have to have the PHP generate Javascript code (the same way it generates HTML) that gets executed after the page is loaded.
echo sqrt(25);
See:
http://php.net/manual/en/function.sqrt.php
Run JavaScript code from PHP
php v8js: https://github.com/phpv8/v8js
$v8 = new V8Js;
$v8->executeString("Math.sqrt('25')"); // 5
https://github.com/chenos/execjs
use Chenos\ExecJs\Context;
$cxt = new Context;
$cxt->eval("Math.sqrt('25')"); // 5
if you have node installed on your server then you can exec this command with php
node a.js
and then use the console.log as output.
Let say I have this JS code:
function plus2(){
print (2+2);
};
So I want to post this code into textarea#input at http://dean.edwards.name/packer/ and then get the result back from textarea#output.
Can use PHP Curl, Shell Curl or JQuery to do the job?
P.S.: By the way, there is bug in PHP Packer port and that's whay I am not using it.
PHP implementation of JSMin works well for me. Also, if you have server-side JS interpreter you can use UglifyJS, it's fast and provides a good compression.
Not really, no. It would need to be passed to a JavaScript engine at some point, so PHP/cURL is not going to be enough.
I recommend using an alternative server-side implementation of packer, or perhaps even YUI Compressor.
I am trying to control stuff with PHP from keyboard input. The way I am currently detecting keystrokes is with:
function read() {
$fp1=fopen("/dev/stdin", "r");
$input=fgets($fp1, 255);
fclose($fp1);
return $input;
}
print("What is your first name? ");
$first_name = read();
The problem is that it is not reading the keystrokes 'live'. I don't know if this is possible using this method, and I would imagine that this isn't the most effective way to do it either. My question is 1) if this is a good way to do it, then how can I get it to work so that as you type on the page, it will capture the keystrokes, and 2) if this is a bad way of doing it, how can I implement it better (maybe using ajax or something)?
edit: I am using PHP as a webpage, not command line.
I'm assuming that you're using PHP as a web-scripting language (not from the command line)...
From what I've seen, you'll want to use Javascript on the client side to read key inputs. Once the server delivers the page to the client, there's no PHP interaction. So using AJAX to read client key inputs and make calls back to the server is the way to go.
There's some more info on Javascript and detecting key presses here and some info on how to use AJAX here.
A neat option for jQuery is to use something like delayedObserver
If you are writing a CLI application (as opposed to a web application), you can use ncurses' getch() function to get a single key stroke. Good luck!
If you're not writing a CLI application, I would suggest following Andrew's answer.
Try readline:
http://us3.php.net/manual/en/function.readline.php
How can I implement jquery in my Zend Framework application in a custom manner.
appending jquery.js ok
appending script ok
send POST data to controller ok
process POSTed data ok
send 'AjaxContext' respond to client now ok (thanks)
I'm using jquery for the first time, what am I doing wrong?
Early on, the best practice to get Zend to respond to ajax requests without the full layout was to check a variable made available via request headers. According to the documentation many client side libraries including jQuery, Prototype, Yahoo UI, MockiKit all send the the right header for this to work.
if($this->_request->isXmlHttpRequest())
{
//The request was made with via ajax
}
However, modern practice, and what you're likely looking for, is now to use one of two new helpers:
ContextSwitcher
AjaxContent
Which make the process considerably more elegant.
class CommentController extends Zend_Controller_Action
{
public function init()
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('view', 'html')
->initContext();
}
public function viewAction()
{
// Pull a single comment to view.
// When AjaxContext detected, uses the comment/view.ajax.phtml
// view script.
}
Please Note: This modern approach requires that you request a format in order for the context to be triggered. It's not made very obvious in the documentation and is somewhat confusing when you end up just getting strange results in the browser.
/url/path?format=html
Hopefully there's a workaround we can discover. Check out the full documentation for more details.
Make sure your using $(document).ready() for any jQuery events that touch the DOM. Also, check the javascript/parser error console. In Firefox it's located in Tools->Error Console. And if you don't already have it installed, I would highly recommend Firebug.
This should have been a comment, can't, yet...
It has nothing to do with ZF+Jquery combination.
First try a proto of what you need with a simple php file. No framework, just Jquery and straight forward, dirty php.
Oh, and don't forget to track what happens with FireBug.