I know there are hundreds of questions about how to pass php variable to JS but i tried a several solution and nothing worked.
I'm pretty new to javascript, i'm using phantomjs to have the URL of an external webpage.
I have this script.js
var page = require('webpage').create();
page.onError = function(msg, trace) {
//prevent js errors from showing in page.content
return;
};
page.open('http://www.google.com', function () {
console.log(page.content); //page source
phantom.exit();
});
called by getweb.php
<?php
exec ('phantomjs script2.js ', $html);
var_dump($html) ;
?>
works perfect.
But If i want to put a php variable in place of google.com it does not work, i guess (just guess...) it's because phantom is no interpreted by navigator.
I tried to put
<script>
var adress = '<?php echo "http://www.google.com" ; ?>';
</script>
before to execute and change my script with
var page = require('webpage').create();
page.onError = function(msg, trace) {
//prevent js errors from showing in page.content
return;
};
page.open(adress, function () {
console.log(page.content); //page source
phantom.exit();
});
but it just take hours without nothing happening.
What can I do to pass a php variable to script.js ?
thanks a lot
I think the best thing to do is pass in extra arguments when you execute Phantom.JS with your script. I can't test in your context, but try something like this. In your PHP:
exec ('phantomjs script2.js "http://example.com/"', $html);
Then in your JavaScript, do a console.log() on system.args. One of them should be http://example.com/. See also: http://phantomjs.org/api/system/property/args.html
Related
This should be a rather straight forward widget with the usual HTML js/div plugin code, but the issue here is that it won't display the echoed PHP code (output would be plain html on callback from the Python file in /cgi-bin/) within Chrome (the browser I'm testing on). When I run the python code below from the BASH shell it displays the echoed PHP code as plain HTML, but it is not displaying anything when I run the Plugin/HTML code below from within Chrome.
cgi.force_redirect = 0 is set within php.ini, so that shouldn't be the issue. Chrome previously threw an error for the PHP code callback due to cgi-bin / php security, but it isn't throwing that error any more with that set in php.ini.
No errors are showing up in Chrome when I run it now, but it just isn't displaying any of the HTML code that should be coming from the PHP echoed code (that should be displayed from the Python callback). There aren't any callback issues as it displays the JSONP when its set to display just a plain string through Python (non-PHP output). So, it's confirmed that it is working to display data across domains.
I don't know Python very well at all, so that could be the issue here. It's a perplexing issue for me and I put in few days trying to figure this all out before coming here to the experts!
Here is the Plugin/HTML code (included on a third party domain (cross domain), not example.com):
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script src="https://example.com/widget/widget.js" type="text/javascript"></script>
<div id="widget"></div>
</body>
</html>
Here is the JavaScript Code (widget.js):
(function() {
// Localize jQuery variable
var jQuery;
/******** Load jQuery if not present *********/
if (window.jQuery === undefined) {
var script_tag = document.createElement('script');
script_tag.setAttribute("type","text/javascript");
script_tag.setAttribute("src",
"https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js");
if (script_tag.readyState) {
script_tag.onreadystatechange = function () { // For old versions of IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
scriptLoadHandler();
}
};
} else {
script_tag.onload = scriptLoadHandler;
}
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
} else {
// The jQuery version on the window is the one we want to use
jQuery = window.jQuery;
main();
}
/******** Called once jQuery has loaded ******/
function scriptLoadHandler() {
// Restore $ and window.jQuery to their previous values and store the
// new jQuery in our local jQuery variable
jQuery = window.jQuery.noConflict(true);
// Call our main function
main();
}
/******** Our main function ********/
function main() {
jQuery(document).ready(function($) {
/******* Load CSS *******/
var css_link = $("<link>", {
rel: "stylesheet",
type: "text/css",
href: "widget-styles.css"
});
// css_link.appendTo('head');
//alert(element);
/******* Load HTML *******/
var jsonp_url = "https://example.com/cgi-bin/widget-python.py?callback=?";
$.getJSON(jsonp_url, function(data) {
$('#widget').html("This data comes from another server: " + data.html);
});
});
}
})(); // We call our anonymous function immediately
Here is the Python code included in /cgi-bin/ and called from widget.js (widget-python.py):
#!/usr/bin/python
import cgi
import subprocess
params = cgi.FieldStorage()
print "Content-Type: text/javascript\n"
proc = subprocess.Popen("php <pathtophpfile>.php", shell=True, stdout=subprocess.PIPE)
result = proc.stdout.read()
jsonp = "%s ( {'html': " + result + " } )"
#jsonp = "%s ( {'html': 'printastring' } )" THIS WORKS and prints into Chrome when its commented out, but its just a string, and what I need is the PHP output from the result variable above.
#print result This prints the php code out perfectly into the command line when I run execute the python script from within /cgi-bin
print jsonp % params['callback'].value
AS FOR THE PHP CODE (pathtophpfile.php) that is supposed to be echoed out into Chrome, its output is pure HTML div to div and it is displaying in the terminal when run, so Python is finding and running the PHP file.. Thank you for your help, and I hope this is enough information, I'll be adding to it if it is not.
Is there a way I can run a php function through a JS function?
something like this:
<script type="text/javascript">
function test(){
document.getElementById("php_code").innerHTML="<?php
query("hello"); ?>";
}
</script>
<a href="#" style="display:block; color:#000033; font-family:Tahoma; font-size:12px;"
onclick="test(); return false;"> test </a>
<span id="php_code"> </span>
I basically want to run the php function query("hello"), when I click on the href called "Test" which would call the php function.
This is, in essence, what AJAX is for. Your page loads, and you add an event to an element. When the user causes the event to be triggered, say by clicking something, your Javascript uses the XMLHttpRequest object to send a request to a server.
After the server responds (presumably with output), another Javascript function/event gives you a place to work with that output, including simply sticking it into the page like any other piece of HTML.
You can do it "by hand" with plain Javascript , or you can use jQuery. Depending on the size of your project and particular situation, it may be more simple to just use plain Javascript .
Plain Javascript
In this very basic example, we send a request to myAjax.php when the user clicks a link. The server will generate some content, in this case "hello world!". We will put into the HTML element with the id output.
The javascript
// handles the click event for link 1, sends the query
function getOutput() {
getRequest(
'myAjax.php', // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
return false;
}
// handles drawing an error message
function drawError() {
var container = document.getElementById('output');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('output');
container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
The HTML
test
<div id="output">waiting for action</div>
The PHP
// file myAjax.php
<?php
echo 'hello world!';
?>
Try it out: http://jsfiddle.net/GRMule/m8CTk/
With a javascript library (jQuery et al)
Arguably, that is a lot of Javascript code. You can shorten that up by tightening the blocks or using more terse logic operators, of course, but there's still a lot going on there. If you plan on doing a lot of this type of thing on your project, you might be better off with a javascript library.
Using the same HTML and PHP from above, this is your entire script (with jQuery included on the page). I've tightened up the code a little to be more consistent with jQuery's general style, but you get the idea:
// handles the click event, sends the query
function getOutput() {
$.ajax({
url:'myAjax.php',
complete: function (response) {
$('#output').html(response.responseText);
},
error: function () {
$('#output').html('Bummer: there was an error!');
}
});
return false;
}
Try it out: http://jsfiddle.net/GRMule/WQXXT/
Don't rush out for jQuery just yet: adding any library is still adding hundreds or thousands of lines of code to your project just as surely as if you had written them. Inside the jQuery library file, you'll find similar code to that in the first example, plus a whole lot more. That may be a good thing, it may not. Plan, and consider your project's current size and future possibility for expansion and the target environment or platform.
If this is all you need to do, write the plain javascript once and you're done.
Documentation
AJAX on MDN - https://developer.mozilla.org/en/ajax
XMLHttpRequest on MDN - https://developer.mozilla.org/en/XMLHttpRequest
XMLHttpRequest on MSDN - http://msdn.microsoft.com/en-us/library/ie/ms535874%28v=vs.85%29.aspx
jQuery - http://jquery.com/download/
jQuery.ajax - http://api.jquery.com/jQuery.ajax/
PHP is evaluated at the server; javascript is evaluated at the client/browser, thus you can't call a PHP function from javascript directly. But you can issue an HTTP request to the server that will activate a PHP function, with AJAX.
The only way to execute PHP from JS is AJAX.
You can send data to server (for eg, GET /ajax.php?do=someFunction)
then in ajax.php you write:
function someFunction() {
echo 'Answer';
}
if ($_GET['do'] === "someFunction") {
someFunction();
}
and then, catch the answer with JS (i'm using jQuery for making AJAX requests)
Probably you'll need some format of answer. See JSON or XML, but JSON is easy to use with JavaScript. In PHP you can use function json_encode($array); which gets array as argument.
I recently published a jQuery plugin which allows you to make PHP function calls in various ways: https://github.com/Xaxis/jquery.php
Simple example usage:
// Both .end() and .data() return data to variables
var strLenA = P.strlen('some string').end();
var strLenB = P.strlen('another string').end();
var totalStrLen = strLenA + strLenB;
console.log( totalStrLen ); // 25
// .data Returns data in an array
var data1 = P.crypt("Some Crypt String").data();
console.log( data1 ); // ["$1$Tk1b01rk$shTKSqDslatUSRV3WdlnI/"]
I have a way to make a Javascript call to a PHP function written on the page (client-side script). The PHP part 'to be executed' only occurs on the server-side on load or refreshing'. You avoid 'some' server-side resources. So, manipulating the DOM:
<?PHP
echo "You have executed the PHP function 'after loading o refreshing the page<br>";
echo "<i><br>The server programmatically, after accessing the command line resources on the server-side, copied the 'Old Content' from the 'text.txt' file and then changed 'Old Content' to 'New Content'. Finally sent the data to the browser.<br><br>But If you execute the PHP function n times your page always displays 'Old Content' n times, even though the file content is always 'New Content', which is demonstrated (proof 1) by running the 'cat texto.txt' command in your shell. Displaying this text on the client side proves (proof 2) that the browser executed the PHP function 'overflying' the PHP server-side instructions, and this is because the browser engine has restricted, unobtrusively, the execution of scripts on the client-side command line.<br><br>So, the server responds only by loading or refreshing the page, and after an Ajax call function or a PHP call via an HTML form. The rest happens on the client-side, presumably through some form of 'RAM-caching</i>'.<br><br>";
function myPhp(){
echo"The page says: Hello world!<br>";
echo "The page says that the Server '<b>said</b>': <br>1. ";
echo exec('echo $(cat texto.txt);echo "Hello world! (New content)" > texto.txt');echo "<br>";
echo "2. I have changed 'Old content' to '";
echo exec('echo $(cat texto.txt)');echo ".<br><br>";
echo "Proofs 1 and 2 say that if you want to make a new request to the server, you can do: 1. reload the page, 2. refresh the page, 3. make a call through an HTML form and PHP code, or 4. do a call through Ajax.<br><br>";
}
?>
<div id="mainx"></div>
<script>
function callPhp(){
var tagDiv1 = document.createElement("div");
tagDiv1.id = 'contentx';
tagDiv1.innerHTML = "<?php myPhp(); ?>";
document.getElementById("mainx").appendChild(tagDiv1);
}
</script>
<input type="button" value="CallPHP" onclick="callPhp()">
Note: The texto.txt file has the content 'Hello world! (Old content).
The 'fact' is that whenever I click the 'CallPhp' button I get the message 'Hello world!' printed on my page. Therefore, a server-side script is not always required to execute a PHP function via Javascript.
But the execution of the bash commands only happens while the page is loading or refreshing, never because of that kind of Javascript apparent-call raised before. Once the page is loaded, the execution of bash scripts requires a true-call (PHP, Ajax) to a server-side PHP resource.
So, If you don't want the user to know what commands are running on the server:
You 'should' use the execution of the commands indirectly through a PHP script on the server-side (PHP-form, or Ajax on the client-side).
Otherwise:
If the output of commands on the server-side is not delayed:
You 'can' use the execution of the commands directly from the page (less 'cognitive' resources—less PHP and more Bash—and less code, less time, usually easier, and more comfortable if you know the bash language).
Otherwise:
You 'must' use Ajax.
I'm developing application using AngularJS. Everything seems to be nice until I meet something that leads me to headache: SEO.
From many references, I found out that AJAX content crawled and indexed by Google bot or Bing bot 'is not that easy' since the crawlers don't render Javascript.
Currently I need a solution using PHP. I use PHP Slim Framework so my main file is index.php which contains function to echo the content of my index.html. My question is:
Is it possible to make a snapshot of rendered Javascript in HTML?
My strategy is:
If the request query string contains _escaped_fragment_, the application will generate a snapshot and give that snapshot as response instead of the exact file.
Any help would be appreciated. Thanks.
After plenty of times searching and researching, I finally managed to solve my problem by mixing PHP with PhantomJS (version 2.0). I use exec() function in PHP to run phantomJS and create Javascript file to take get the content of the targeted URL. Here are the snippets:
index.php
// Let's assume that you have a bin folder under your root folder directory which contains phantomjs.exe and content.js
$script = __DIR__ ."/bin/content.js";
$target = "http://www.kincir.com"; // target URL
$cmd = __DIR__."/bin/phantomjs.exe $script $target";
exec($cmd, $output);
return implode("", $output);
content.js
var webPage = require('webpage');
var system = require('system');
var page = webPage.create();
var url = system.args[1]; // This will get the second argument from $cmd, in this example, it will be the value of $target on index.php which is "http://www.kincir.com"
page.open(url, function (status) {
page.onLoadFinished = function () { // Make sure to return the content of the page once the page is finish loaded
var content = page.content;
console.log(content);
phantom.exit();
};
});
I recently published a project that gives PHP access to a browser. Get it here: https://github.com/merlinthemagic/MTS. It also relies on PhantomJS.
After downloading and setup you would simply use the following code:
$myUrl = "http://www.example.com";
$windowObj = \MTS\Factories::getDevices()->getLocalHost()->getBrowser('phantomjs')->getNewWindow($myUrl);
//now you can either retrive the DOM and parse it, like this:
$domData = $windowObj->getDom();
//this project also lets you manipulate the live page. Click, fill forms, submit etc.
I'm trying to get JSON array from my php-script. Following is my Jquery code written in my jsp file-
$(document).ready(function()
{
alert("Inside Ready");
$.getJSON('http://example.com/root_dir/test_json.php', function(data)
{
alert(data);
});
});
but, above code showing only outer alert (i.e. alert("Inside Ready");) and not showing inner alert (i.e. alert(data); ). I'm getting expected json when I hit URL in browser. So definitly there is no problem in URL and php-script.
following is test_json.php
<?php
//Create an array
$json_response = array();
$row_array['label'] = 'A';
$row_array['value'] = $row['0 to 2'];
$row_array['color'] = '#FA2020';
array_push($json_response,$row_array);
$row_array['label'] = 'B';
$row_array['value'] = $row['2 to 3'];
$row_array['color'] = '#2BD95A';
array_push($json_response,$row_array);
$row_array['label'] = 'C';
$row_array['value'] = $row['above 3'];
$row_array['color'] = '#F7F739';
//push the values in the array
array_push($json_response,$row_array);
echo json_encode($json_response);
?>
Getting following json when I hit URL in browser-
[{"label":"A","value":"19","color":"#FA2020"},{"label":"B","value":"1","color":"#2BD95A"},{"label":"C","value":"2","color":"#F7F739"}]
I'm using jquery-1.10.2.js. Thank You..!
Try This one...Hope so it is useful to you
$(document).ready(function()
{
$.ajax({
type:'POST',
url:'http://example.com/root_dir/test_json.php',
dataType:'JSON',
data:{
},
success:function(data1){
alert(data)
},
error:function(XMLHttpRequest,textStatus,errorThrown){
alert("error");
}
});
});
Your code seems to be working fine -
I just created a test page with your code and it works -
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
alert("Inside Ready");
$.getJSON('http://<<CHANGE SERVER NAME>>/zz-test/get_json.php', function(data)
{
alert(data);
});
});
</script>
</head>
<body>
</body>
</html>
Your jQuery and PHP code looks fine so, in my experience, it is usually an error caused by calling your PHP script from a different domain (i.e.: file:///). If you can access your browser's console, you should be able to see if this is in fact the error causing the data not to be displayed.
One solution for this is to add at the top of your PHP code:header('Access-Control-Allow-Origin: *');. There are however some security concerns with this, so it should not be used permanently.
Alternatively, you could upload all your HTML, CSS, JS, jQuery, etc. code to the web server hosting the PHP file, which is a far better option.
Finally, if the option above is not possible you could use JSON-P (although this does not work with POST requests), there is a question about this at Simple jQuery, PHP and JSONP example?
I am trying to execute a js action that automatically sends informations to the URL for future use with php. To do so, I added a "onload" event on the window object and modified the URL in the listener. This is what it looks like so far:
window.addEventListener("load", function() {
window.location = "?test=test";
}, false);
When I load the page, the URL changes, but this is repeated over and over until the browser crashes. I was just wondering if there was a way to only execute it once.
If you don't want to use AJAX, and don't want to write JS functions to parse query strings, why not a simple:
<?php if(!isset($_GET['test'])): ?>
<script>
window.addEventListener("load", function() {
window.location = "?test=test";
}, false);
</script>
<?php else: ?>
<!--No JS written on the page, so no redirect -->
<?php endif;?>
But you really should look into AJAX, try using some JS framework like jQuery to help you in the process: http://api.jquery.com/jquery.ajax/
Check to see if you're already ON that page, before redirecting.
Add a simple flag on the URL like so: window.location = "?test=test&second=true";
As suggested in How can I get query string values in JavaScript?
Write a function to check get the URL params in JS GetQueryStringParams()
Then as suggested by others pass a send param in while reload
window.location = "?test=test&second=true";
Use the function in JS to check if you have a URL query string second and if its not there then reload the page
if you want to pass variables do this:
<?php
if(!isset($_GET['page'])){ //this line check if the variable field is available
$a = "Blank";
}else{
$a = $_GET['page'];
}
?>
that is it.
You could just erase the onLoad method once it's run, like so:
<script>
function doLoadStuff()
{
doSomeStuff();
//Clear onLoad contents
body.onLoad = function() {};
}
</script>
<body onLoad="doLoadStuff();">MyContent</body>