PHP-PhantomJS: Twig_Error_Runtime? - php-phantomjs

I'm learning php-phantomjs and am gettting a Twig_Error_Runtime. Here's my PHP:
$location = '/Applications/myWebApp/js/phantomjsTest.proc';
$serviceContainer = ServiceContainer::getInstance();
$procedureLoader = $serviceContainer->get('procedure_loader_factory')
->createProcedureLoader($location);
$client->getProcedureLoader()->addLoader($procedureLoader);
$request = $client->getMessageFactory()->createRequest();
$request->setType('phantomjsTest');
$response = $client->getMessageFactory()->createResponse();
$client->send($request, $response);
if ($response->getStatus() === 200) {
// Dump the requested page content
echo $response->getContent();
}
...and here's my .proc file:
phantom.onError = function (msg, trace) {
console.log(JSON.stringify({
"status": msg
}));
phantom.exit(1);
};
var system = require('system');
var uri = "http://www.jonnyw.me";
var page = require('webpage').create();
page.open(uri, function (status) {
console.log(JSON.stringify({
"status": status
}));
if (status === "success") {
page.render('example.png');
}
phantom.exit(1);
});
phantom.exit(1);
What am I missing? Thanks in advance to all for any info.

I got it working by replacing this:
$request->setType('phantomjsTest');
...with this:
$client->setProcedure('phantomjsTest');

Related

Return created item key

My app creates a new item, and I want to retrieve the key to use in a server script. The data variable returns null though. This is what I have:
function addItem(addButton) {
var addItemPage = addButton.root;
if (!addItemPage.validate()) {
return;
}
var props = addItemPage.properties;
var itemDs = addItemPage.datasource;
props.Creating = true;
itemDs.saveChanges({
success: function(key) {
props.Creating = false;
if (app.currentPage !== app.pages.EditItem) {
return;
}
var newProjectItem = itemDs.item;
newProjectItem._loadHistory();
gotoEditItemPage(newProjectItem._key, true);
return newProjectItem;
},
failure: function(error) {
props.Creating = false;
console.error(error);
}
});
gotoEditItemPage();
var data = app.datasources.ProjectItems.item._key;
google.script.run.withSuccessHandler(function(value){
alert("Created");
}).createDoco(data);
}
This is not neat by any means, but I fixed it by creating a new function:
function addItem(addButton, key) {
var addItemPage = addButton.root;
if (!addItemPage.validate()) {
return;
}
var props = addItemPage.properties;
var itemDs = addItemPage.datasource;
props.Creating = true;
itemDs.saveChanges({
success: function() {
props.Creating = false;
if (app.currentPage !== app.pages.EditItem) {
return;
}
var newProjectItem = itemDs.item;
newProjectItem._loadHistory();
gotoEditItemPage(newProjectItem._key, true);
var key = newProjectItem._key;
value(key);
},
failure: function(error) {
props.Creating = false;
console.error(error);
}
});
gotoEditItemPage();
function value(record){
var data = record;
google.script.run.withSuccessHandler(function(value){
alert("Created");
}).createDoco(data);
}
}

Correct Way to Pass Script to PhantomJS via PHP-PhantomJS?

I'm learning PhantomJS and PHP-PhantomJS. I want to pass a script to PhantomJS.
Currently I'm trying this:
$client->getEngine()->addOption('/Applications/myWebApp/js/phantomtest.js');
$request = $client->getMessageFactory()->createRequest('http://www.jonnyw.me/', 'GET');
$response = $client->getMessageFactory()->createResponse();
$client->send($request, $response);
if ($response->getStatus() === 200) {
echo $response->getContent();
}
I'm getting an empty $response object back after the call to $client->send($request, $response).
Here's the contents of my test script ('phantomtest.js'):
var page = require('webpage').create();
page.open('http://www.jonnyw.me', function(status) {
console.log("Status: " + status);
if(status === "success") {
page.render('example.png');
}
phantom.exit();
});
I think this must be the relevant page in the docs: http://jonnnnyw.github.io/php-phantomjs/4.0/4-custom-scripts/
Here is code that is working:
In PHP:
$location = '/Applications/myWebApp/js/';
$serviceContainer = ServiceContainer::getInstance();
$procedureLoader = $serviceContainer->get('procedure_loader_factory')
->createProcedureLoader($location);
$client->getProcedureLoader()->addLoader($procedureLoader);
$request = $client->getMessageFactory()->createRequest();
$client->setProcedure('phantomJStest');
$response = $client->getMessageFactory()->createResponse();
$client->send($request, $response);
if (($response->getStatus() === 200) || ($response->getStatus() == 'success')){
// Dump the requested page content
echo $response->getContent();
}
In the proc file phantomJStest.proc:
phantom.onError = function (msg, trace) {
console.log(JSON.stringify({
"status": msg
}));
phantom.exit(1);
};
var system = require('system');
var uri = "http://www.jonnyw.me";
var page = require('webpage').create();
page.open(uri, function (status) {
console.log(JSON.stringify({
"status": status
}));
if (status === "success") {
page.render('example.png');
}
phantom.exit(1);
});

Update dynamic data in service-worker.js

I have the below data coming in form of array from a url.
[{"title":"hey hi","body":"hello","url":"https://simple-push-demo.appspot.com/","tag":"new"}]
service-worker.js
it has the above url in fetch()
'use strict';
console.log('Started', self);
self.addEventListener('install', function(event) {
self.skipWaiting();
console.log('Installed new', event);
});
self.addEventListener('activate', function(event) {
console.log('Activatednew', event);
});
self.addEventListener('push', function(event) {
try{
console.log('Push message', event);
var ev = event;
//sample
return fetch("http://localhost/push-notifications-master/app/json.php").then(function(ev,response) {
response = JSON.parse(JSON.stringify(response));
return response;
}).then(function(ev,j) {
// Yay, `j` is a JavaScript object
console.log("j", j);
for(var i in j) {
var _title = j[i].title;
var _body = j[i].body;
var _tag = j[i].tag;
console.log("_body", _body);
}
ev.waitUntil(
self.registration.showNotification("push title", {
body: _body,
icon: 'images/icon.png',
tag: _tag
}));
});
return Promise.all(response);
}
catch(e){console.log("e", e)}
});
I am trying to see the above array data coming from that particular url in console.log("j",j);. but it shows undefined. How can i get dymanic data in sw.js Please Guide.
In your addEventListener('push' .... method, I think it might be better to wait for a response before parsing it.
Also, to be checked, but your php request should be in https (not checked by myself, but my request are on https).
Here how I do this :
event.waitUntil(
fetch('YOUR PHP URL').then(function(response) {
if (response.status !== 200) {
console.log('Problem. Status Code: ' + response.status);
throw new Error();
}
// Examine the text in the response
return response.json().then(function(data) {
if (data.error || !data.notification) {
console.error('The API returned an error.', data.error);
throw new Error();
}
var title = data.notification[0].title;
var body = data.notification[0].body;
var icon = data.notification[0].icon;
var notificationTag = data.notification[0].tag;
return self.registration.showNotification(title, {body: body,icon:icon, tag: notificationTag});
});
})
);
The json :
{"notification" : [{"title":"TITLE","body":"BODY","icon":"URL TO ICON","tag":"TAG"}]}
Hope it can be useful.

meteor bindenvironnement issue

getTime: function () {
host="http://www.xxxxxx.com/";
res= Meteor.bindEnvironment(function(){
var Fiber = Meteor.require('fibers');
var Future = Meteor.require('fibers/future');
var future = new Future();
request(host, function (error, response, body) {
Fiber(function(){
if (!error && response.statusCode == 200) {
$ = cheerio.load(body);
var $thumbs = $('.thumb');
for (var i = 0, l = $thumbs.length ; i < l ; i++) {
// elements
var $thumb = $($thumbs[i]);
// save info
videourl=host+$thumb.find('a').attr('href');
videothumbs = [$thumb.find('img').attr('src')];
videos=Videos.insert({title:videoTitle,thumbs:videothumbs,lastUpdated:Date.now()});
}
return videos;
}
else {
return "error";
}
}).run()
});
}) ;
return res;
}
This is a server side method and returning undefined
Without bindenvironment it is returning error to use bindenvironemnt.
Am I using it properly, can somebody tell m the modifications in my code
You need a future to return the value of inner function:
Meteor.methods({
getTime: function() {
var future = new Future();
Meteor.bindEnvironment(function() {
future.return('Some value');
});
return future.wait();
},
});
Check out this Meteorpad for an example.
If you use suggestion from #saimeunt comment, then your code could be simplified into form:
SERVER:
Meteor.methods({
getSite:function(url){
var site = HTTP.get(url);
console.log("statusCode =\n " , site.statusCode);
console.log("content.length =\n ",site.content.length);
console.log("header =\n ",site.headers);
$ = cheerio.load(content);
...
}
})
CLIENT :
Meteor.call("getSite", "http://www.google.com");
See how it works

jquery in visual studio 2012 ultimate and mvc 3

i need to ask something and i am getting stucked of this:
This is my controller code :
public ActionResult FastRegister(FormCollection collection)
{
UserModel db = new UserModel(0);
string str = "";
//Boolean
//Common.IsAlphaNumeric_Dot_Underscore()? er
errorInsert err = new errorInsert();
try
{
db.set_value(0, Common.HtmlFormUrlEncode(collection["user_name"]), Common.HtmlFormUrlEncode(collection["user_pass"]), "", "", Common.HtmlFormUrlEncode(collection["user_email"]), "", DateTime.Now, "", Common.RandomString(false), 0);
db.Insert();
err.duplicate = false;
err.error = "success register";
return Json(err, JsonRequestBehavior.AllowGet);
}
catch (Exception exception)
{
if (exception.Message.Contains("unique") == true && exception.Message.Contains("duplicate") == true)
{
err.duplicate = true;
err.error = "username or email already taken";
}
else
{
err.duplicate = false;
err.error = exception.Message;
}
return Json(err, JsonRequestBehavior.AllowGet);
}
}
}
class errorInsert
{
public Boolean duplicate;
public string error;
public errorInsert()
{
}
}
and this is my jquery code :
<script type="text/javascript">
$(document).ready(function(){
function ajax_send_url(user_name, user_pass, user_email)
{
$.ajax({
type: 'POST',
url: 'http://localhost/smile/User/FastRegister',
data: 'user_name='+user_name+'&user_pass='+user_pass+'&user_email='+user_email,
//contentType: 'application/json; charset=utf-8',
success: function(e)
{
//var x=jQuery.parseJSON(e);
$("#loading").html(e.error);
}
, dataType:"json"
, beforeSend:function (e){$("#loading").html('<img src="loading.gif" width="50px">');}
});
}
$("#register").click
(
function()
{
var user_name = $("#user_name").val();
var user_pass = $("#user_pass").val();
var user_email = $("#user_email").val();
ajax_send_url(user_name,user_pass,user_email );
}
);
});
I've got in my firebug 200 OK Http but no response when i checked. Please someone figure it out and help me. Thanx...

Resources