How to use a javascript function in a pure php page - php

I am looking for a way to include a .js function with in a straight php page. By straight php I mean there is no html included.
Explanation of process if you will.
I have a page where employees must swipe their ID badge for access to a computer.
The employee swipes the badge, the magnetic strip is read, and the data sting is sent to the db to get the access levels etc. This works great unless I get a bad card read. What I have is a .js file that pulls the ID and the issue date of the badge from the data string and validates it before going to the db. If it fails it errors.
At the error point I will ask them to swipe the card again etc...
So back to the top, can I use this .js file in a php file.
If not, can someone point me to a library or chart where I can find the comparison values for js and php. (.js - var s = ""; | .php $s = ""; etc...)

Can't you implement the validation logic in php:
<?php
function validateId($id = null) {
// your validation code goes here
if($id != null) {
// Code to be executed for a successful swipe
echo "success";
} else {
// Code to be executed for a failed swipe
echo "An epic failure occurred. Please swipe again";
}
}

I think your best bet would be to install a server-side JS engine and then run it using system.
A reasonable example is Narwhal. If you install that on your server, then you can do something like this from PHP:
system('js /path/to/my/js/file.js',$retval);
The only thing you may have to modify is any case where your JS interacts with the browser (i.e. document.writes, DOM manipulation), but Narwhal has equivalents for interacting with the CLI.

Related

call php from ajax javascript

I have a PHP-based template website that has been heavily modified.
I am in the process of adding some RSS feeds, most of which are easy to "interpret" and display satisfactorily but one is in caps with "pre" formatting as well.
I want to modify the content. I look at all the mods I make as education and invariably am able to google satisfactory solutions to the problems I come across but, despite an earlier extensive programming background, without a thorough grounding in Javascript, Ajax, PHP, CSS and HTML, there are sometimes things that just frustrate the hell out of me.
All I want to do is pass a block of text from javascript code to PHP code, massage it and get the result back.
I am at a point in a ajax/jscript function where...
items[i].content
...contains the block of text that I want massaged and I have a piece of code that I got from here, I think, that ostensibly calls the PHP code...
function compute() {
var params="session=123";
$.post('wxspellch.php',params,function(data){
alert(data);//for testing if data is being fetched
var myObject = eval('(' + data + ')');
document.getElementById("result").value=myObject(addend_1,addend_2);
});
...and, unfortunately, it isn't documented so I don't have a clue what has to be customized. All I have done so far is enter the name of my PHP script.
The PHP script is written like this...
$pspell = pspell_new('en','american','','utf-8',PSPELL_FAST);
function spellCheckWord($word) {
global $pspell;
$autocorrect = TRUE;
// Take the string match from preg_replace_callback's array
$word = $word[0];
etc......
}
function spellCheck($string) {
return preg_replace_callback('/\b\w+\b/','spellCheckWord',$string);
}
echo spellCheck("...... the data .......")
The PHP tests out fine with hard-coded data.
I just need to know what further customizing I have to do to the javascript and php in order to facilitate the passing and recovery of the block of text.

Sharing access restrictions between php and javascript

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;
?>

does a PHP page with includes get compiled and sent as one page?

I have a PHP page where the header and footer are PHP includes.
I want to know if there is any possibility of the includes loading asynchronously - or does PHP gather all the files required, compile them and send them as one file?
The reason I ask is that I've seen an interesting PHP app that seemed to keep the connection open and do things in sequence before closing the connection - I wondered if that's what happens with includes.
PHP version is 5.3.6
EDIT:
What I actually want is for the page to load all at once, to prevent my layout mashing as each bit loads. Sorry to any who misunderstood this
PHP does gather and compile them; everything goes to the browser as a single document. If you don't want this, you'll have to do something with XMLHTTPRequest on the frontend
Generally any output will be output as it is generated.
echo 'A';
sleep(1000);
echo 'B';
sleep(1000);
echo 'C';
This slowly outputs "ABC". Includes are included when they are encountered, the same way echo outputs anything at that specific point. It's all in order, never asynchronously.
A web server may buffer all output before sending any of it to the client. In the above example, you'd receive "ABC" all together after 2 seconds of nothing.
If your objective is to receive all the page at once you need to use ob_start() and ob_end_flush(). Do something like:
ob_start();
...
write all your outputs
...
ob_end_flush();
This will force the server to buffer the output until the whole page is prepared.
Good luck!
I use the following architecture when loading a page on my application:
index.php
<script src="path/to/js/lib/jslib.js" type="text/javascript"></script>
window.addEvent('load', function()
{
BuildPg(PgStatus); //PgStatus is a variable I use in a state machine to build different pages
});
<form>
<div id="DivPgTop"></div>
<div id="DivPgMiddle"></div>
<div id="DivPgBottom"></div>
</form>
This is the entire index.php
In my jslib.js I have functions like:
function BuildPg(Pg) {
BuildPgTop(Pg);
BuildPgMiddle(Pg);
BuildPgBottom(Pg);
}
function BuildPgTop(Pg) {
var Content="";
if (Pg == 1) {
Content = function_a(); // function_a builds the top of the page
else if (Pg == 2) {
Content = function_b();
etc...
}
document.getElementById("DivPgTop").innerHTML = Content; //here is where I load the top of the page
}
And I do the same for the other parts of the page Middle and Bottom.
Using this framework, if you changed my BuildPg() function to something like:
function BuildPg(Pg) {
BuildPgTop(Pg);
sleep(foo);
BuildPgMiddle(Pg);
sleep(bar);
BuildPgBottom(Pg);
}
Your user would experience the top of the page loading first, a delay, the middle of the page, another delay, and the bottom.
And if you change the order of the function calls you could even have the bottom of the page load first, then the middle and the top.
I hope this makes sense. Good luck!
PHP sends a single document. What you want to do is achieved with something called AJAX (http://en.wikipedia.org/wiki/Ajax_%28programming%29)
Basically you write some JavaScript code that uses XMLHTTPRequest object to connect to the server and download some extra info.

How to setup split test?

I want to create a way to test different layouts on a page to see which get more conversions.
For example. If I have 2 versions of a page and I send 50% to page A and 50% to page B and see which one converts more sales.
So I am thinking maybe use .htaccess to rewrite half to page A and the other half to page B.
But how can I do that with .htaccess is there a way? do I need to use PHP instead to do this?
Also if there is a better way to do this, or any cautions I should be aware of, please let me know.
Lots of ways to deal with it on your own code. If however you're already using Google Analytics and don't care to use javascript for the test, spare yourself a lot of trouble and look at http://www.google.com/websiteoptimizer/index.html
Update (Reconfine): Google website optimizer no longer exists, this has been replaced with "Google Analytics content experiments" https://developers.google.com/analytics/devguides/platform/experiments-overview
I would do that using php, following way:
After the user got to the default php file, i would store his browser data in a db table, and the active layout identifier (filename, row id, etc...).
Everytime the server gets a request from this user, it shows the page, mapped to him.
But! If you have two independent pages, i would only store how many people visited site one, and site two, and redirect them to page A, and to page B by a 50% division.
If you've got a supported database and are using PHP 5.2 or later, you can use a free split testing library called phpScenario, found at www.phpscenario.org
Then you write more or less something like this:
require_once 'scenario_setup.php'; // you write this
if (Scenario::IsControl('experimentname')) {
// read and output version 1
} else {
// read and output version 2
}
Then when you get to your conversion point (say, sign up):
require_once 'scenario_setup.php'; // same
Scenario::Complete('experimentname');
And to view the stats (probably on your admin page):
require_once 'scenario_setup.php'; // yup
Scenario::RenderXml('experimentname');
I think php will be very useful. For example, you can use rand or push a variable in a file :
$int = file_get_contents('var');
if ($int) {
$int++;
} else{
$int = 1;
}
if (($int % 2) == 0) {
header('Location: url1);
} else {
header('Location: url2);
}
file_put_contents ('var', $int);
With apache, you have to setup a load balancer : http://httpd.apache.org/docs/2.1/mod/mod_proxy_balancer.html
I would use php personally. Then you can save which page layout you chose for them as a session var making it easy to load that layout on each page refresh. You would probably also want to save into the database with their username (if they login) and if they visit later show them the same layout.

PHP work with JS Jquery

How do i make PHP work with JS?
I mean more like, i want to check if the user is logged in or not,
and if he is then it will:
$("#message").fadeIn("slow"); ..
How should i do this?
I have an idea maybe have a file that checks it in php, and then it echo out 1 or 0.
And then a script that checks if its getting 1 then do the message fade in.. But im not as so experienced to script that in JS
You cannot directly pass variables from Javascript to PHP because the PHP run on the server before it's sent to the client. But you can 'pass' variables from PHP to Javascript.
For example:
echo('<script type="text/javascript'> var phpvar = '.$variablefromphp.';</script>');
However, you can manipulate what javascript your browser will print. You can first check if the user is logged in in PHP, and based on that, conditionally print the HTML and Javascript.
For example
if($user->logged_in())
{
echo('<script type="text/javascript">$("#message").fadeIn("slow");</script>');
}
else
{
//php function
generateLoginBox();
}
I only javascript to enhance user experience. You should make your application work even when javascript turned off.
With the javascript enabled, you can add an enhanced experience, such as animated page element, AJAX request, etc.
In case of login state, you should have a way to know it in PHP script. Then in the output, you can have a conditional block that only executed if the login state is true. You can put anything you want here.
Javascript can be working in a static HTML page. You can use this to create a simple test for the code that you wrote, to see if it working as you want. Read the documentation in http://www.jquery.com/, there are many links there to many examples.

Categories