Loading and changing iFrame 'src' from another page - javascript

I have a page with an iFrame and four links to native files that each appear correctly within the iFrame when summoned. I've done this with straight HTML. The problem is that when I land on the page initially I have an empty iFrame until I click any of the links.
Not only would it be nice to have the iFrame populated with the first link upon arrival, but it would be a real bonus if there was a way to arrive at this page with any other of the remaining links appearing, if in fact that's the content someone came looking for. For example, if I place anchors for my four links on another page, it would be ideal if someone could select the second item and find it populating the iFrame upon arrival at my-iFrame-page.php.
I'm not opposed to using jQuery nor javascripting of any kind, but I'm afraid that for a scripting novice, it's important that I understand the syntax. I'd be over the moon if someone could post a working example that achieves what I'm after.

You can set the src="" attribute for the iframe which will set the default page.
For example, if I place anchors for my four links on another page, it would be ideal if someone could select the second item and find it populating the iFrame upon arrival at my-iFrame-page.php.
Needless to say, if you have a preceding page which links to that which contains the iframe, you can pass the url selected as a parameter in the request to the iframe page and then parse it into the attribute with PHP.
For simplicity's sake, let's imagine that you have two pages: sourcepage.php and framepage.php. sourcepage.php contains a form with four radio buttons plus a submit button which submits to framepage.php. The radio buttons are all part of the same set, and have four values--as per your comment "Apples", "Bananas", "Cherries" and "Peaches". The Apples radio has a value of 1, Bananas 2 and so on. Each radio has the name "page".
What this means is that when you submit the form, on sourcepage.php you need the following code
<?php
$pageIndex = $_GET["page"];
$pageUrl = "";
switch ($pageIndex)
{
case "1":
$pageUrl = "apples.html";
break;
case "2":
$pageUrl = "bananas.html";
break;
// And so on...
}
?>
<!-- And then later... -->
<iframe src="<?php echo $pageUrl; ?>"></iframe>

Use JS to get an URL paramater, and ofcourse add a paramater to the links in your footer. Assuming your iframe has id="iframe", this does the trick :)
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script>
$(document).ready(function() {
function get_url_param(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null) {
return "";
} else {
return results[1];
}
}
if (get_url_param('show') == '') {
$('#iframe').attr('src', 'wall-structures.php'); // Setting your default page....
} else {
$('#iframe').attr('src', get_url_param('show') + '.php');
}
});
</script>
</head>
<body>
Wall & Structures<br />
Ovens & Barbecures<br />
Pillars & Arches<br />
Stairs & Retaining Walls<br />
<iframe id="iframe"></iframe>
</body>
</html>
If you don't want to use JS, it can also be done in pure PHP:
<?php
if (isset($_GET['show'])) {
$iframe_src = $_GET['show'] . '.php';
} else {
$iframe_src = 'somedefaultpage.php';
}
?>
Wall & Structures<br />
Ovens & Barbecures<br />
Pillars & Arches<br />
Stairs & Retaining Walls<br />
<iframe src="<?php echo $iframe_src; ?>"></iframe>

Related

How do I have a child webpage receive a variable value from a parent webpage?

For my school project I'm creating a mockup cinema website that has ticket booking service. Currently I'm trying to create the seat selection part.
I've successfully done that, and how the code detects if a seat has been selected is a Boolean value. (e.g. if they selected seat A1, a variable named "A1" will be set to true), now the only part left is to transfer the selection details users have selected to a popup webpage where they fill in their "payment" details. How do I exactly transfer variable values to a child webpage? Is a php file needed? I'm a noob at php so some guidance is appreciated.
I've been searching this technique for a while online(inc. stack overflow), but I couldn't find any right code that is right for my situation
<html>
<body>
The on/off button:
<button onclick="press_button"><img id="button" src="on.png" style="width:100px"></button>
<BR>
The button that opens a new webpage:
<button onclick="confirm()"> Confirm</button>
<script language="JavaScript">
var i=0, status;
function press_button(){
i++;
if(i%2 == 1){
document.getElementById('button').src='off.png';
status=true
}
else
document.getElementById('button').src='on.png';
status=false
}
//function that changes the look of the button when it is on/off and records down whether it is on/off
function confirm(){
window.open("confirm.html")
//opens a new webpage
</script>
</body>
</html>
For simplicity, I've made a simple web page that has an on/off button, and I'd like to have a confirm button that opens a new page and displays a text message depending on the status of the on/off button. Can anyone teach me how to do that?
You can do this with JS alone, but there are many other approaches too.
<body>
<input type='text' value='defaultParamValue'>
<button type='button'>send param</button>
<script type='text/javascript'>
document.querySelector('button').onclick
= () => window.location.href
= 'destination.html?nameOfParam='
+ encodeURIComponent(document.querySelector('[type=text]').value)
</script>
</body>
You can do this with PHP, which is more realistic and practical.
<body>
<form action='destination.php' method='get'>
<input name='param' type='text' value='defaultParamValue>
<input type='submit'>
</form>
</body>
And this is how you retrieve the value with PHP at destination.php.
$_POST['param'];
Here is how to do it with your own example.
<body>
The on/off button:
<!-- you need to include type='button', otherwise it acts as type='submit' -->
<button type='button' onclick='press_button()'>
<img id='button' src='on.png' style='width:100px'>
</button>
<BR>
The button that opens a new webpage:
<!-- you need to include type='button', otherwise it acts as type='submit' -->
<button type='button' onclick='confirm()'> Confirm</button>
<script type='text/javascript'> // the language attribute is deprecated
var
i=0,
button=document.querySelector('button'),
status
function press_button(){
i++
if(i%2 == 1){
button.src='off.png'
status=true
}
else{ // you were missing a curly bracket
button.src='on.png'
status=false
}
} // you were missing a closing curly bracket
function confirm(){
if(status){
// window in window.open is a global variable
// which means it is always accessible
// and you do not need to include it
open(`confirm.html?status=${encodeURIComponent(status)}`)
}
} // you were missing a closing curly bracket
</script>
</body>
Structuring your code makes it easier to spot issues (i.e. missing curly brackets) in your code.
The following JS will allow you to obtain the URL query string parameters on the new page.
const
urlParams = new URLSearchParams(location.search),
myParam = urlParams.get('status')
console.log(urlParams) // status=true/false
console.log(myParam) // true/false

Make duplicate html document with autogenerated name

Essetially, I am building a very rudimentary website builder that uses forms on a page to manipulate the HTML of the page,displayed below the input boxes, which eventually the user can get the source of to put onto their own website. I have not built it yet, but I was thinking that I would need more than one template in case anyone was trying to edit the same template at the same time, and having their edits overridden by others using the program. Here is a mockup for your leisure:
Html Displayed below input:
<h1 class="heading">Hi guys!</hi>
Form mockup:
<input id="headingEdit">
<script>
document.getElementById("heading").innerHTML = document.getElementById("headingEdit").value;
</script>
My problem is one that may or may not be relevant, and that is that should someone want to edit this template, when someone else is also editing it, then surely the html would keep on getting overridden by each other, and no-one would get anywhere. What I therefore want to do is be able to, when a user clicks on the 'Edit this Template' button on the homepage, they are taken to a randomly generated page, which is an exact duplicate of a master page, make their edits, and then that page is deleted, or (when I add integration) stored in a users account.
This might be a duplicate question, but the answer has not come up in my research so far.
Thanks in advance.
you can use AngularJS
http://www.w3schools.com/angular/default.asp
<!DOCTYPE html>
<html>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="">
<p>Input something in the input box:</p>
<p>Name : <input type="text" ng-model="name" placeholder="Enter name here"></p>
<h1>Hello {{name}}</h1>
</div>
</body>
</html>
Here's a short PHP solution
$pageid = uniqid();
copy('template.html', $pageid . '.html');
print "Editable page is at: " .$pageid . ".html";
Add this somewhere in the template.html:
<?php
if (str_replace(' ', '', preg_replace('/\.html/', '', basename($_SERVER['PHP_SELF']))) !== 'template') {
print "<script>
var elems = document.getElementsByTagName('*'),
i;
for (i = 0; i < elems.length; i += 1) {
elems[i].setAttribute('contentEditable', 'true');
}
window.onbeforeunload = function(){
var a = new XMLHttpRequest() || new ActiveXObject('Microsoft.XMLHTTP');
a.onreadystatechange = function (b) {
if(a.readyState==4&&a.status==200){
}
}
xmlhttp.open('POST','remove_template.php',true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send('id=" . str_replace(' ', '', preg_replace('/\.html/', '', basename($_SERVER['PHP_SELF']))) . "');
}
//Custom JavaScript goes here
</script>";
}
?>
Then remove_template.php is:
if ($_POST['id'] != 'template' && ctype_alnum($_POST['id'])) {
unset($_POST['id']);
}
You should obviously change what urls to your needs, also remove_template.php is kinda insecure. I haven't tested this yet. If you ever add a user system. Made the $pageid link to their user account. Then just pass an if to not add the window.onbreforeunload
If you can't support PHP you can use an icky JavaScript solution
window.editPage () { document.body.contentEditable='true'; document.designMode='on'; }
window.savePage () { localStorage.setItem('savedPage', document.body.innerHTML); }
window.getPage () { document.body.innerHTML = localStorage.getItem('savedPage'); }
Then you can add the function to the onclick attribute
<div onclick="window.editPage()">Edit Page</div>
I've found something called Surreal CMS (Content Management System) which might be what you want. Or maybe something like create.js

function variable not passing to global variable

Good day all, I've two pages of php file and an external javascript file. I want to pass a selected radio button's value to a jquery global variable so that I can view the div element which has the same id as selected radio button's value. Whenever I click PLAY! button I don't see my div element on the next page. Here are my codes:
player-choose.php script:
<head>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/mycustom.js"></script>
</head>
<body>
<div id="player-list">
<input type="radio" name="player" value="fighter" id="fighter-radio"><label for="fighter-radio"><img src="images/heroes/fighter-01.png" width="74" height="70"></label>
<input type="radio" name="player" value="pakhi" id="pakhi-radio"><label for="pakhi-radio"><img src="images/heroes/pakhi.png" width="95" height="70"></label>
</div>
<button id="play">PLAY!</button>
</body>
mycustom.js script:
var playerID;
function start(){
spawnhero();
}
$(function(){
$("#play").click(function(){
window.location.href = 'index.php';
playerID = $('input[name=player]:checked').val();
});
})
function spawnhero () {
$("#content").append($("<div>").attr('id', playerID));
}
index.php script:
<head>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/mycustom.js"></script>
</head>
<body onload="start()">
<div id="content">
<div id="galaxy"></div>
</div>
</body>
It's a very simple thing but I don't know why it's not working. Am I doing something wrong here? Please if anyone finds a solution enlighten me. Tnx!
If you're moving to a new page (window.location = ...), you'll need some slightly more complicated way of transferring information between those pages - for the most part, HTTP/HTML is "stateless", with the exception of technologies like cookies. JavaScript variables get wiped out entirely - it's actually re-parsing the entire JQuery library on each new page (not to say that's something to avoid)
For a video game, as long as player information doesn't include server components (I could be wrong) my recommendation would be saving player information in sessionStorage.
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage
However, if this is a server-based game in which your choice of player matters beyond the local computer, you'd likely want to send the player ID to the server, either by structuring the page request differently:
window.location.href = 'index.php?playerId=' + playerId;
Or by POSTing the data as a form; most easily accomplished by structuring your submit button as an <input type="submit">, and wrapping all your <input> elements in a <form method="POST"> object.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form
From there, your server software could write the second page's response out differently based on the given information - you can even customize what JavaScript is written inside of a <script> tag using PHP directives.
var playerId = "<?php print($_POST['playerId']); ?>";
Hopefully that helps get you started.
global variables are not persistent across pages. Once you load your index.php , it will have the new global scope(window variable).
I suggest passing a parameter.
$("#play").click(function(){
playerID = $('input[name=player]:checked').val();
window.location.href = 'index.php?id=' + playerID;
});
afterward, inside your index.php script , read the parameter and assign accordingly.
Alternative solution is you could you use JavaScript or jQuery cookie or localstorage. You can get/set values across page loads/redirects but these are not passed to server.
jQuery Cookie
var playerID = $('input[name=player]:checked').val();
$.cookie("playerId", playerID);
LocalStorage
var playerID = $('input[name=player]:checked').val();
localStorage.setItem("playerId", playerID);

PHP: Reading DOM info of own HTML page

So, let's say I have only one file on my server called index.php :
<!DOCTYPE html>
<html>
<body style="background-color: orange;">
<!-- On/Off button's picture -->
<?php
echo ("<img id='button' src='data/button.jpg' alt='off'/>");
?>
</body>
</html>
Now, let's say I attach a JavaScript that changes the buttons ALT to ON when I click the button at some point.
How can I read the DOM elements on this page using PHP?
So far, I've found this code:
$dom = new DOMDocument;
$dom->loadHTML($html);
$main = $dom->getElementById('alt');
but I can't figure out how I would fit that in my code above, what page should I call loadHTML() for?
How do I make PHP read DOM elements it generated using echo?
First of all, your button has id button, so searching for the id alt would return no results.
Second: The piece of php you found reads a page $html (probably file_get_contents('some_url'), puts it in the variable dom and parses it, searching for the id alt. In your case it would read your own page, breaking it down in pieces looking for that button.
Thats of no use if you can read the status with javascript on your own page. You can then pass it to php trough an ajax-call or by adding it to the url like mypage.php?button=off
$main = $dom->getElementById('button');

Google CSE - search box that redirects to the page with results

guys.
I'm a bit confused with Google CSE manual and can't understand some of its basic functionality.
So, I have created a free custom search profile and all I got is the only code snippet, this one:
<div id="cse" style="width: 100%;">Loading</div>
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load('search', '1', {language : 'ru', style : google.loader.themes.V2_DEFAULT});
google.setOnLoadCallback(function() {
var customSearchOptions = {};
var googleAnalyticsOptions = {};
googleAnalyticsOptions['queryParameter'] = 'q';
googleAnalyticsOptions['categoryParameter'] = '';
customSearchOptions['googleAnalyticsOptions'] = googleAnalyticsOptions; var customSearchControl = new google.search.CustomSearchControl(
'001098741616107095995:xeqdxoqdue8', customSearchOptions);
customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
customSearchControl.draw('cse');
}, true);
</script>
This snippet creates the google custom search controls in the specified div. That's why this snippet is probably going to be situated in the search results page, e. g. www.site.com/search.html
But what I'm going to implement is the search box in the sidebar on every page of my website. User can type-in the search query into that search box wherever he is and get straight to the result page www.site.com/search.html with the set of matches awaiting him.
How can I do that?
Looking through the manual has no effect for me, I'm missing something, but can't figure out what exactly...
Thanks!
The google search works by getting the search query from a URL parameter. You just need to create a form that posts get parameters to your results page. The name of your search field needs to match the one in the URL bar normally a q like www.yoursite.com?q=your+search
<form action="http://www.yoursite.com/resulspage" method="get">
Search: <input type="text" name="q" />
<input type="submit" value="Seacrh" />
</form>
here something that worked for me. ( if I understood correctly your Q )
src="https://www.google.com/jsapi">
.........
customSearchControl.draw('google_search');
<? if (isset($keyword)) { ?>
customSearchControl.execute('<?=$keyword?>'); <? } ?>
}
google.setOnLoadCallback(OnLoad);
</script>

Categories