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">';
}
Related
i want to pass PHP variable to Javascript array.
It is a test code, but in further i want to pass the printed product id's and name's to this ajax function to send it to cart
The code above is working without printing the button with echo.Any better ideas are welcome :)
<html>
<?php
$num=3;
echo "<button onclick='funkt('<?php echo $num ?>');'>cc</button>
";
?>
</html>
<script>
function funkt(x){
var c=x;
alert(c);
}
</script>
You weren't properly escaping the quotes inside the echo statement. Also, HTML attributes use double quotes (onclick="..."), not single quotes.
Try this:
<!DOCTYPE html>
<html>
<head>
<script>
function funkt(x) {
var c = x;
alert(c);
}
</script>
</head>
<body>
<?php
$num = 3;
echo "<button onclick=\"funkt('" . $num . "');\">cc</button>";
?>
</body>
</html>
Better option is to add an input field of type hidden and pass the number/name/ID to it. On submission of form or button click, you can fetch it wtih the field Id and pass the value to ajax.
<input type="hidden" id="number" value="<?php echo $num;?>" />
<script>
function funkt(x) {
var c = document.querySelector("#number").value;
alert(c);
}
</script>
You can try to declare variable inside "script" tag, and then use this variable in the javascript afterwards like this:
<?php $num = 5; ?>
<script>
var link_label = '<?php echo $num ?>';
//use your link_label value to load it in ajax here or in other files that has been loaded after this script
</script>
I am working on a webpage that takes HTML form input, processes it on a loop using PHP, then displays the PHP echo output in a div using jQuery, then TTS speaks a message using ResponsiveVoiceJS.
The problem that is visible right now is that, upon loading of the page, the TTS starts speaking the webpage file name and some random PHP on a loop, then displays the form twice.
It shouldn't do any of that!
Since I am not sure which part of the code is causing the issue, here is the code in its entirety:
<html>
<head>
</head>
<body>
<form action="<?php
echo $_SERVER['PHP_SELF'];
?>" method="post">
What is your URL? <input type="text" name="pastedurl"><br>
What is your minimum interval? <input type="text" name="interval"><br>
<input type ="submit">
</form>
<?php
set_time_limit(18000);
if (isset($_POST['submit']))
{
// echo "stopped here";
// die; //THIS DOESN'T WORK EITHER
$pastedlink = $_POST['pastedurl'];
$pastedlink2 = $_POST['pastedurl'];
$rate = $_POST['interval'];
parse_url($_POST['pastedurl'], PHP_URL_HOST);
if (parse_url($_POST['pastedurl'], PHP_URL_HOST) == 'www.instructables.com')
{
for ($z = 0; $z < 2880; $z++)
{
$tutorial_json = file_get_contents($pastedlink);
$tutorial_array = json_decode($tutorial_json, true);
$oldviews = $tutorial_array['views'];
sleep(30);
$tutorial_json2 = file_get_contents($pastedlink);
$tutorial_array2 = json_decode($tutorial_json2, true);
$currentviews = $tutorial_array2['views'];
$viewcount1 = (int) $oldviews;
$viewcount2 = (int) $currentviews;
$change = $viewcount2;
$change -= $viewcount1;
$rateasint = (int) $rate;
if ($change >= $rateasint)
{
$sayit = "Alert! Your Tutorial has gained " . $change . " more views";
echo $sayit;
}
}
}
else
{
exit("Error: URL submitted was not from www.instructables.com");
}
}
?>
<script src="http://code.responsivevoice.org/responsivevoice.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script>
$(document).ready(function(readyEvent) {
speakInnerHTML();
});
function speakInnerHTML() {
var speek = document.getElementById("load_updates");
responsiveVoice.speak(speek.innerHTML);
}
</script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#load_updates').load('<?php
echo $_SERVER['PHP_SELF'];
?>',speakInnerHTML).fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
<div id="load_updates"> </div>
</body>
</html>
Sorry about the poor formatting, I am a noob and don't know the methods of formatting these programming languages!
Here is a video of the error in action:
youtube
1.
die; //THIS DOESN'T WORK EITHER
die() is a function, and despite the wonders of echo, all functions are called with parentheses.
2.
isset($_POST['submit'])
This doesn't work because there are variables with the name submit.
To fix that, add the name attribute to your submit control, like this:
<input type="submit" name="submit">
3. You are loading the page itself with jQuery, even though it contains... well... itself. It's going to recursively fill the page with its own instances every 10000ms. And every one of that instance is going to do that too. You need to query the page with the data from the form, not just load it. And add a conditional so that if there is $_POST data, the page does not display all the HTML.
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";
}
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
Example:
I have written a php script like below:
<?PHP
function _hello(){ "Hello world!"; }
function _bye(){ "Good Bye!"; }
function _night(){ "Good Night!"; }
?>
<html>
<head>!-- required files -- </head>
<body>
<div id="thisDIV">
<? echo _hello(); ?>
</div>
<div>
This is another Division.
</div>
</body>
</html>
Is it possible that I just want to reload the function _hello() in the division (id=thisDIV) by using javascript? Or ajax, Jquery ajax or whatever.. How can I make it? Thanks!
You could add a querystring to your URL and then tie that to what function you want to run:
eg: http://myurl.com/page.php?function=hello
In page.php:
$function = $_GET['function'];
if($function == "hello") {
hello();
}
etc etc