Casperjs Passing Data Back to PHP

CasperJS passing data back to PHP

You can redirect output from stdout to an array.

On this page it says you can do:

string exec ( string $command [, array &$output [, int &$return_var ]] )

It goes on to say:

If the output argument is present, then the specified array will be filled with every line of output from the command.

So basically you can do exec('casperjs command here, $array_here);

Pass parameter from php to casperjs/phantomjs

I found the answer myself.

It seems phantomjs and casperjs support command line arguments http://phantomjs.org/api/system/property/args.html

My script now looks like this.

test.php

$user_input = $_POST['user_input'];

putenv("PHANTOMJS_EXECUTABLE=/usr/local/bin/phantomjs");
exec('/usr/local/bin/casperjs hello.js $user_input 2>&1',$output);

print_r($output);

hello.js

var system = require('system');
var args = system.args;
var address = args[4]; //In my case 4 was the argument for $user_input, yours might be different, depending on your server setup.

var casper = require('casper').create({
verbose: true,
logLevel: 'error',
pageSettings: {
loadImages: false,
loadPlugins: false
}
});

casper.start(address, function() {
this.echo(this.getTitle());
});

casper.run();

Installing casperJS and phantomJS in WIndows Apache 2.4 to pass data to PHP

So I ended up figuring out the proper path to casperJS and phantomJS. I placed both of the .exe in C:\casperjs\bin and did not even need to add them to my PATH, and it worked very well. This is my index.php, which sends AJAX for a php page executing my casperJ-script (I have added a counter for each successful/failed test, as well as allowed the user to select how frequently the test should run):

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css" type="text/css" media="screen, projection"/>
<link rel="shortcut icon" type="image/ico" href="favicon_jdoe.png" />
<script src="jquery-2.1.1.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript" src="jquery.dropdownPlain.js"></script>
<title>CasperJS Automated Testing Unit</title>
</head>
<center>
<body>
<div id="mainContent">
<p>Welcome to the CasperJS Automated Testing Unit</p>
<br>
<button id="button_AJAX">Run CasperJS</button>
<button id="button_STOP" onclick="myStopFunction()" style="display: none">Stop CasperJS</button>
</div>

<p>
<select id="multi">
<option value="1">1 min</option>
<option value="2">2 min</option>
<option value="5">5 min</option>
<option value="10">10 min</option>
<option value="30" selected="selected">30 min</option>
<option value="60">1 hour</option>
<option value="360">6 hours</option>
<option value="720">12 hours</option>
<option value="1440">1 day</option>
</select>
</p>

<p>
<div class="centered">
<div style="float:left; margin-right:20px">
<div style="float:left">Success count:</div>
<div id="succcount" style="float:left">0</div>
</div>
<div style="float:left">
<div style="float:left">Fail count:</div>
<div id="failcount" style="float:left">0</div>
</div>
</div>
</p>

<br>

<br>
<div id="loading"></div>
<script type="text/javascript">

var succcount = 0;
var failcount = 0;

$('#button_AJAX').click(function executecasperJS() {
$('#loading').html('<img src="rays.gif"><br><i>Web harvesting in progress; please wait for test results.</i>'); // Loading image
$.ajax({ // Run ajax request
type: "GET",
dataType: "text",
url: "casperJS.php",
success: function (data) {
$('#loading').html(data);

if( data.indexOf('Fail: 0') !== -1 ) {
succcount++;
} else {
failcount++;
}
$('#succcount').html(succcount);
$('#failcount').html(failcount);
}
});

multi = $( "#multi option:selected" ).val();
console.log("multi="+multi);

timeout = setTimeout(executecasperJS,multi*60000); //1 min == 60000
});
$("#button_AJAX").click(function() {$("#button_AJAX").text("CasperJS Executed");});
$("#button_STOP").click(function() {$("#button_AJAX").text("Run CasperJS");});
function myStopFunction() {
clearTimeout(timeout);
}

$("#button_AJAX").click(function(){
$("#button_STOP").show();
});

$("#button_STOP").click(function(){
$("#button_STOP").hide();
});

</script>
</div>
<div id="page-wrap">
<ul class="dropdown">
<li><a href="#">CasperJS Logs</a>
<ul class="sub_menu">
<li><a href="casperjs_log.txt" target="_blank">Testing Log</a></li>
<li><a href="casperjs_error.txt" target="_blank">Error Log</a></li>
</ul>
</div>
</center>
</body>
</html>

and here is the casperJS.php; which sends out an email if a failure occurs:

<?php

set_time_limit(3600);

date_default_timezone_set('America/New_York');
$date = date('m/d/Y h:i:s a', time());
$time_start = microtime(true);
$output = exec("C:\casperjs\bin\casperjs casperJScript.js");
if (strpos($output, 'Fail: 0') === FALSE) {
require_once('PHPMailer_5.2.4/class.phpmailer.php');
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 1;
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;
$mail->IsHTML(true);
$mail->Username = "email@host.com";
$mail->Password = "password";
$mail->SetFrom('email@host.co');
$mail->AddReplyTo("email@host.co");
$mail->Subject = "casperJS: Server failure occured on $date";
$mail->Body = "The casperJS testing unit has picked up a server fault: $output
$mail->AddAddress("email@host.co");
if(!$mail->Send()) {
//echo "Mailer Error: " . $mail->ErrorInfo;
} else {
// echo "An error has occured and an email with the fault has been sent.";
echo '<span style="color:#FF0000">An error has occured; it was logged and an email notification has been sent.</span>';
$userip = $_SERVER['REMOTE_ADDR'];
$file = 'casperjs_error.txt';
$oldContents = file_get_contents($file);
$fr = fopen($file, 'w');
$txt = "ERROR log: $output. Requested by: $userip on $date." . PHP_EOL . PHP_EOL ;
fwrite($fr, $txt);
fwrite($fr, $oldContents);
fclose($fr);
echo "<br />";
echo "<br />";
}
}
echo "Test Results: $output";
$userip = $_SERVER['REMOTE_ADDR'];
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "<br />";
echo "<br />";
echo "Last test completed in $time seconds\n on $date";
$file = 'casperjs_log.txt';
$oldContents = file_get_contents($file);
$fr = fopen($file, 'w');
$txt = "Log: $output. Test completed in $time seconds\n on $date. Requested by: $userip" . PHP_EOL . PHP_EOL ;
fwrite($fr, $txt);
fwrite($fr, $oldContents);
fclose($fr);
?>

Using casperjs and PHP to save data

Not sure to fully understand your question (see my comment above it), but basically:

var casper = require('casper').create();
var username = 'foo';
var password = 'bar';

casper.start('http://service.domain.tld/register.html', function() {
this.fill('form[action="/register"]', {
'username': username,
'password': password
}, true);
});

casper.then(function() {
if (/Your account was created/.test(this.fetchText('.success'))) {
this.echo('Created account: ' + username + '/' + password);
} else {
this.echo('Failed creating account for ' + username);
}
});

casper.run();

You could also return some JSON serialization of any supplementary information to ease their consumption by a PHP script.

Send data from CasperJS script to PHP

Not 100% on CasperJS, but looking at your PHP code try using json_encode in your script like this:

$casperjs = "casperjs";
$script = 'add_site.js';
$arg0 = $_POST['new_site'];
$command = "$casperjs $script $arg0";
$result = shell_exec($command);
echo json_encode($result);

Also try setting explicit JSON headers for your output like this:

$casperjs = "casperjs";
$script = 'add_site.js';
$arg0 = $_POST['new_site'];
$command = "$casperjs $script $arg0";
$result = shell_exec($command);
$json_data = json_encode($result);
header('X-JSON: (' . $json_data . ')');
header('Content-type: application/x-json');
echo $json_data;

Clicking a button to run casperJS in PHP and echo results in same PHP page with button

So I figured that I could use AJAX to display the casperjs echoed results in the same page. I made an HTML page with two buttons: 1) Run casperjs AJAX to run the AJAX, and 2) Run casperjs to simply load a PHP page executing the casperjs script and printing the results in a new page. Here is the HTML (with help from How to link external javascript file onclick of button for AJAX button click):

<!DOCTYPE html>
<html>
<head>
<title>casperJS testing</title>
</head>
<center>
<body>
<div id="mainContent">
<p>Welcome to the Automated Testing Utility</p>
<table>
<tr>
<td><button id="button_AJAX">Run casperjs AJAX</button></td>
<td><form action="runscript.php">
<input type="submit" value="Run casperJS">
</form></td>
</tr>
</table>
</div>
<script type="text/javascript">
var button = document.getElementById('button_AJAX');
button.onclick = function(){
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "casperjsajax.js";
document.getElementsByTagName("head")[0].appendChild(script);
return false;
}
</script>
</center>
</body>
</html>

The casperjsajax.js code (with the aid of JS Essential Training):

// 1: Create the request 
var myRequest;

// feature check!
if (window.XMLHttpRequest) { // does it exist? we're in Firefox, Safari etc.
myRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // if not, we're in IE
myRequest = new ActiveXObject("Microsoft.XMLHTTP");
}

// 2: Create an event handler for request to call back
myRequest.onreadystatechange = function(){
if (myRequest.readyState === 4) {
var p = document.createElement("p");
var t = document.createTextNode(myRequest.responseText);
p.appendChild(t);
document.getElementById("mainContent").appendChild(p);
}
};

// Open and send it
myRequest.open('GET', 'scriptresults.php', true);
// any parameters?
myRequest.send(null);

The scriptresults.php code:

<?php
echo "Here are your test results!";
echo "<br />";
echo exec("/home/user/casperjs/bin/casperjs /full/path/to/your_script.js");
?>

And the runscript.php link for non-AJAX

<html>
<head>
<title>casperJS Test Results</title>
</head>
<body>
<center>
<p>Here are your results!</p>
<br>
<?php
echo exec("/usr/local/bin/casperjs /full/path/to/your_script.js");
?>
</center>
</body>
</html>


Related Topics



Leave a reply



Submit