how to put javascript as function parameter - javascript

For some reasons, I have to set page head section from another include page.
First look at inc.php page below:
page: inc.php
<?php
function sethead($javascript){
echo '<html><head>';
echo '<link rel="stylesheet" type="text/css" href="site.css" />';
echo '<script type="text/javascript" src="jquery1.9.1.js"></script>';
echo $javascript;
echo '</head>';
}
?>
The inc.php page contains sethead() function which will set head for each page like this:
page: main.php
<?php
include('inc.php');
$javascript = '<script type="text/javascript" language="javascript">.......</script>';
sethead($javascript);
<body>
Here body codes go here
.....................
.....................
.....................
</body>
</html>
?>
The main.php page could be any page, like secondpage.php, thirdpage.php .... and so on.
But as the javascript for each page might be different, so I have to echo this javascript from the function parameter of sethead($javascript). But I could not find a suitable way to declare this javascript parameter in main.php page before calling the function sethead($javascript) because the javascript code consists of several line of codes which are difficult to put in a variable.
<script type="text/javascript" language="javascript">
document.oncontextmenu = function() {
return false;
}
window.onbeforeunload = function() {
return "Please don't reload this page.";
}
</script>
How can I put the above lines of javascript code in a variable/function parameter ($javascript) in a easy way?

If you just want an easier why to define a multi-line variable, use NOWDOC:
$javascript = <<<'EOD'
<script type="text/javascript" language="javascript">
document.oncontextmenu = function() {
return false;
}
window.onbeforeunload = function() {
return "Please don't reload this page.";
}
</script>
EOD;
Although it might be easier to write the javascript in an external .js-file and pass the filename to include instead.

PHP supports multiline strings, so you can simply white:
$javascript = '
<script type="text/javascript" language="javascript">
document.oncontextmenu = function() {
return false;
}
window.onbeforeunload = function() {
return "Please don\'t reload this page.";
}
</script>
';
And don't forget to escape all ' symbols.
But I think the best decision would be keep js-code in a js-file

Related

How to pass variables from PHP to Javascript redirect

I've put together this short little code that should randomly pick a url from "url.txt" and then redirect it through a javascript redirect. For whatever reason I can't get it to work. I'm aware of how to get it to work with other forms of redirection including meta refresh and php header, however I would like to know how to do with with javascript redirection.
<?php
$loadlist = explode("\n", file_get_contents('urls.txt'));
$rand = rand(0,count($loadlist)-1);
$picked = $loadlist[$rand];
?>
<html>
<head>
<script type='text/javascript'>
window.location.href = '<?php echo $picked ?>'
</script>
</head>
</html>
<?php
$loadlist = explode("\n", file_get_contents('urls.txt'));
$rand = rand(0,count($loadlist)-1);
$picked = $loadlist[$rand];
?>
<html>
<head>
<script type='text/javascript'>
window.location.replace("<?php echo $picked ?>");
</script>
</head>
</html>
Try this

Echoed Javascript Code from PHP Via AJAX Not Running

My code is meant to get the author of an inputted book using the Google Books API via AJAX. If nothing is inputted it prints "Empty". What it actually does is print out the Javascript code when a book is inputted. When nothing is inputted, it prints "Empty" as it should. How could I modify my code to make the echoed Javascript execute and hence get the author of an inputted book?
Just to see, I replaced the echo part with echo "<script>document.getElementById('txtBox').innerHTML = 'Hello';</script>";. It also prints out the javascript code, so I don't think it has something to do with using the API.
getAuthor.html
<!DOCTYPE html>
<html>
<body>
<!-- Input -->
<div class="form">
<form onsubmit="makeRequest(); return false">
<input type="text" id="inputText" name="inputText">
<input type="submit">
</form>
</div>
<br>
<!-- Output -->
<div class="txtBox">
<textarea id="txtBox">
</textarea>
</div>
<!-- AJAX to create output using jEcho.php file-->
<script>
function makeRequest() {
httpRequest = new XMLHttpRequest();
console.log(httpRequest.responseText);
httpRequest.onreadystatechange = function() {
document.getElementById("txtBox").innerHTML = httpRequest.responseText;
};
httpRequest.open("POST", "jEcho.php", true);
httpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");
httpRequest.send("inputText=" + document.getElementById("inputText").value);
}
</script>
</body>
</html>
jEcho.php
<?php
$input = $_POST["inputText"];
if ($input == "") {
echo "Empty";
} else {
// used to parse
// e.g. The Rosie Project -> The+Rosie+Project
$temp = str_replace(" ", "+", $input);
// create appropiate source
$scriptSource = "https://www.googleapis.com/books/v1/volumes?q=$temp&callback=handleResponse";
echo "<script>
function handleResponse(response) {
var item = response.items[0];
document.getElementById('txtBox').innerHTML = item.volumeInfo.authors[0];
}
</script>
<script src='$scriptSource'></script>";
}
?>
Links
Echoing Javascript From PHP:
How to call a JavaScript function from PHP?
Echoing javascript from PHP
Google Books API:
https://developers.google.com/books/docs/v1/getting_started
https://developers.google.com/books/docs/v1/using
<script> elements are only run when your page is first loaded. Script elements created later on, either by assigning to an element's .innerHTML, creating them using document.createElement(), or otherwise, are not executed.
If you want to have a PHP script send back code to be evaluated, you'll have to do that directly, e.g:
httpRequest.onreadystatechange = function() {
eval(httpRequest.responseText);
};
(And remove the <script> tags from the response.)
Try setting header in jEcho.php file (not tested)
header('Content-Type: application/javascript');
I'm not allowed to comment so:
I'm not certain what has caused it for but could <script src='$scriptSource'></script>"; be called before the handleResponse function. I'm not too sure what is causing it, at the moment, that is my best idea.
Also could you not just have the url already in the code like this: (jEcho.php)
<?php
$input = $_POST["inputText"];
if ($input == "") {
echo "Empty";
} else {
// used to parse
// e.g. The Rosie Project -> The+Rosie+Project
$temp = str_replace(" ", "+", $input);
// create appropiate source
//$scriptSource = "https://www.googleapis.com/books/v1/volumes?q=$temp&callback=handleResponse";
echo "
<script src='https://www.googleapis.com/books/v1/volumes?q=$temp&callback=handleResponse'></script>
<script>
function handleResponse(response) {
var item = response.items[0];
document.getElementById('txtBox').innerHTML = item.volumeInfo.authors[0];
}
</script>";
}
?>

converting the result of a javascript function into a usable variable

I have this code which returns on a click of a button the URL of an iframe
<html>
<body>
<iframe src="start.php" name="vframe" id="vframe"></iframe>
<script>
function glink() {
alert(document.getElementById('vframe').contentWindow.location.href);
}
</script>
<button onclick="glink()">Click me</button>
</body>
</html>
What I want to do is somehow use the javascript function to create a variable (the link it captures via the onclick) inside the function without the need for an onclick that can be used in the parent page
For example
<html>
<body>
<iframe src="start.php" name="vframe" id="vframe"></iframe>
<script>
function glink() {
var x = document.getElementById('vframe').contentWindow.location.href;
}
</script>
Then I can use var x in this way ...
<script> if ($link =="start.php") { echo '<img src="start.jpg">' } else {
echo '<img src="end.jpg">' }
</script>
</body>
</html>
Obviously, the javascript is somehow able to get the link, but I need to get it programmatically and not have to rely on a 'click', and I need to be able to hold the link in a variable so I can use it in a conditional statement, as noted above.
I am not too familiar with javascript syntax.
====
Edited
====
I tried this (based on DevishOne's suggestion):
<html>
<body>
<iframe src="start.php" id="vframe"></iframe>
<script>
function glink() {
var x = $('#vframe').attr('src');
$.get('processIframeLink.php',{link:x});
}
</script>
<?
$link = $_REQUEST['link'];
echo $link;
if ($link =="start.php") {
echo '1';
} else {
echo '2';
}
?>
</body>
</html>
But there is nothing showing at '$_REQUEST['link'];'
however I just tried this:
<html>
<body>
<? $test = '<p id="demo"></p>';
echo $test;
?>
<iframe src="start.php" name="vframe" id="vframe"></iframe>
<script>
document.getElementById("demo").innerHTML = document.getElementById('vframe').contentWindow.location.href;
</script>
</body>
</html>
Here, echo $test returns the result of the script. But for some reason, it keeps returning "about:blank"
If there was some way to get "document.getElementById('vframe').contentWindow.location.href;" to show the iframe link, then I have accomplished the goal.
I have found "document.getElementById('vframe').contentWindow.location.href;" in many places on the net saying it can get the iframe link, but I keep getting "about:blank"
==========
edit
Here is the latest attempt:
<html>
<body>
<iframe src="start.php"></iframe>
<script>
function glink() {
var x = frames[0].location;
document.getElementById("demo").innerHTML = x;
}
</script>
<button onclick="glink()">Click me</button>
<? $link = '<p id="demo"></p>'; ?>
echo '<p id="demo"></p>';
?>
</body>
</html>
What this does is (upon the click), allows the JS to find the link and then the PHP reads it as a variable. The only issue here is if there is no 'click', frames[0].location; = "about:blank" ... if there is a click, then the code writes the link to the PHP variable.
how to 'read' the link without the click or to simulate a click to bring in the link, that would be ideal.
The problem with your question is that JS cannot directly communicate with PHP.
PHP page is rendered instantly, and JS is rendered WHILE page is being loaded, through your Web browser.
To solve this problem you need to use either Ajax or jQuery and use POST or GET functions through POSTBACK functions.
They allow you to send information to secondary page, while fetching results and rendering those results into the primary page.
HTML
<script>
function glink() {
var x = $('#vframe').attr('src');
$.get('processIframeLink.php',{link:x});
}
</script>
PHP (processIframeLink.php)
$link = $_REQUEST['link'];
if ($link =="start.php") {
echo '<img src="start.jpg">';
} else {
echo '<img src="end.jpg">';
}

How do I pass a variable from one php file to a javascript file?

I am currently trying to make a site where I put in info in on my html side, it send the info to the php file and grabs info from another site depending on what you put in on the html side.
To make this more clear this is how it works:
You put in your username in the html site(where the javascript code
is).
Then it sends your username to the php file.
The php file gets the information, puts it in a link and request it.
It grabs information from this request (highscores page).
This is where it stops.
I don't know how to return the information to my javascript file.
This is my code:
html/javascript page:
<html>
<head>
<script type="text/javascript" src="./aloticcalc_files/jquery.min.js"></script>
</head>
<body>
<script>
function test() {
var username = "Exzib";
window.location.href = "grabinfo.php?username=" + username;
}
</script>
</body>
</html>
This is my php file: (grabinfo.php)
<html>
<head>
</head>
<?php
$username = $_GET['username'];
include_once('simple_html_dom.php');
if(isset($_GET['name'])) {
$html = file_get_html('https://alotic.com/hs/?name='.$username);
$xp = $html->find('td', 10);
$formatxp = $result=str_replace(array('$',',','.',' '),'',$xp);
echo $formatxp;
}
?>
<body>
</body>
</html>
So how do I proceed to send the $formatxp to my javascript?
Thanks
So what you do is execute:
window.location.href = "grabinfo.php?username=" + username;
This causes the browser to navigate to grabinfo.php and display the information that you want. Except that you don't want the information to be displayed, you want to retrieve it into a JavaScript variable, right?
To do so, don't set window.location.href. Instead call your script using AJAX. You'll find plenty of tutorials on AJAX out there. This will allow you to capture the output of your PHP script.
Change the following line
$formatxp = $result=str_replace(array('$',',','.',' '),'',$xp);
to
$formatxp = str_replace(array('$',',','.',' '),'',$xp);
And to pass the variable to Javascript you can do something like this.
<script type="text/javascript">
var $formatxp = '<?php echo $formatxp; ?>';
</script>
Write a script tag and set the variable equal to your PHP variable.
<script>
var thing = '<? echo $formatxp; ?>';
</script>
This is going to be easy as you already include jQuery. (Using ajax)
Look
<html>
<head>
<script type="text/javascript" src="./aloticcalc_files/jquery.min.js"></script>
</head>
<body>
<label>Type your username:<input id="username" type="text"></label>
<input id="submit-button" type="button" value="Get my highscores!">
<p id="response"></p>
<script>
//When user clicks "submit-button" button
$("#submit-button").on('click', function() {
var username = $("#username").val();
//We request our php with the username
$.get("grabinfo.php?username=" + username, function(xpValue) {
//When we receive the response from php then we add it to a "p" tag
$("#response").text("LOL your xp is: "+xpValue+". NOOOOOOOB!!");
});
});
</script>
</body>
</html>
And that's it!
More info at http://api.jquery.com/on/
And http://api.jquery.com/get/
http://api.jquery.com/text/
http://api.jquery.com/val
And well the whole jQuery API documentation http://api.jquery.com
EDIT:
OH. You have to change grabinfo.php. It should only have this:
<?php
$username = $_GET['username'];
include_once('simple_html_dom.php');
if(isset($_GET['name'])) {
$html = file_get_html('https://alotic.com/hs/?name='.$username);
$xp = $html->find('td', 10);
$formatxp = $result=str_replace(array('$',',','.',' '),'',$xp);
if(empty($formatxp)) {
echo "ERROR: Invalid could not find xp with username {$username}";
}
else {
echo $formatxp;
}
}
else {
echo "ERROR: Invalid arguments";
}

opening new window in PHP not working

I am trying to open a new window in PHP by echoing what i need, because im placing information from my database in the URL.
I can get this to work in plain HTML, JS but as soon as i try and echo out the line it doesnt call the function, im sure im missing something obvious.
Got the code from here http://www.quirksmode.org/js/popup.html
Thanks
<script language="javascript" type="text/javascript">
<!--
function popitup(url) {
newwindow=window.open(url,'name','height=400,width=600');
if (window.focus) {newwindow.focus()}
return false;
}
// -->
</script>
<?php
echo "<a href = 'popupex.html' onClick='return popitup(\'popupex.html\')'‌​>234</a>";
?>
You had two hidden characters before your > in )'‌​>234 which could contribute to the problem. (Consult Footnotes).
Plus, I replaced (\'popupex.html\') to (\"popupex.html\") with escaped double quotes. Leaving them as single quotes did not make the window to pop up when testing.
The two hidden characters: ‌​
This works with both hidden characters removed. (tested)
Copy the code below, do not replace with what you already have.
<script language="javascript" type="text/javascript">
<!--
function popitup(url) {
newwindow=window.open(url,'name','height=400,width=600');
if (window.focus) {newwindow.focus()}
return false;
}
// -->
</script>
<?php
echo "<a href = 'popupex.html' onClick='return popitup(\"popupex.html\")'>234</a>";
?>
Footnotes:
Leaving the hidden characters in the code would show up as this in the HTML source:
'??>234
Use this code:
<script language="javascript" type="text/javascript">
<!--
function popitup(url) {
newwindow=window.open(url,'name','height=400,width=600');
if (window.focus) {newwindow.focus()}
return false;
}
// -->
</script>
<?php
echo "<a href = 'popupex.html' onClick='return popitup(\"popupex.html\")'‌​>234</a>";
?>
<?php
if(something): //if you received data from database
//here you can also add value from database
$phpvalue = "data from database";
//you can popup php value or just add your target url instead of $phpvalue
?>
Test
<?php else:
if(SOMETHINGELSE)
?>
<?php endif ?>

Categories