is there any way to change urls is iframe? - php

I want to show a page of my website within iframe in another page.
I mean you can see helper.html while you are navigation main.php.
but I want to change some links in helper.html regarding to some conditions set in main.php.
The regular solution is to get content of helper.html and process it in main.php, then echo it.
But it is server side, I want this process to be client side.
Is that possible with JavaScript?

If your files are located at the same domain, you can use the top.frames property, ro refer to the window object of named frames:
Assume the top HTML to has such a structure:
<iframe name="main" /><iframe name="helper" />
Inside main:
top.frames["helper"].document.getElementById("linkID").href = "http://newlink.com";
If you're using AJAX, you can add the previously shown code in the callback handler. If main.php reloads on change, at the code within <script> tags.

If those files are on different domains but you have a full control of them, then use the following solution:
In the main page call an iframe with GET parameters. For instance:
<iframe src="foo.html?parameter=value" width="400" height="500"></iframe>
In an iframe parse GET parameters using Javascript and show an appropriate content:
// get the current URL
var url = window.location.toString();
//get the parameters
url.match(/\?(.+)$/);
var params = RegExp.$1;
// split up the query string and store in an
// associative array
var params = params.split("&");
var queryStringList = {};
for(var i=0;i<params.length;i++)
{
var tmp = params[i].split("=");
queryStringList[tmp[0]] = unescape(tmp[1]);
}
// print all querystring in key value pairs
for(var i in queryStringList)
document.write(i+" = "+queryStringList[i]+"<br/>");
Source: http://www.go4expert.com/forums/showthread.php?t=2163

Try this...
var myIframe = document.getElementById('SomeIFrame');
myIframe.src = 'www.joobworld.com';

Yes it is possible if both frames are in same domain.
See sample function: in the help frame the id of link is assumed to be "link"
function ChangeLink()
{
var Helpframe = document.getElementById("Helpframe");
var innerDoc = Helpframe.contentDocument || Helpframe.contentWindow.document;
var link = innerDoc.getElementById("link");
link.href="http://www.google.com";
}
This solution is inspired from Javascript - Get element from within an iFrame

Related

PHP id value get without page refresh

I want to access php id on the same page for this i want something like this:
href="?id='.$row["id"].'"
but i want to show popup and not want the page to get refresh so i can show my result on my popup on the same page.
href="#?id='.$row["id"].'" // using hash will not make it work.
Any help would be appreciated.
you can add a rel parameter to anchor tag and get that parameter using jquery or javascript.
<a href="javascirpt:void(0)" class="item" rel="id_$row["id"]" />
$('a.item').click(function() {
var getvalue = $(this).attr('rel');
});
I had the same issue. Use this:
<a href="javascirpt:void(0)" rel='.$row["id"].' class="showpopup">
$(".showpopup").click(function(ev)
{
var getid = $(this).attr('rel'); // get id value
alert(getid); // check to see if you are getting the value.
ev.preventDefault();
}
thats it enjoy :)
Parameter preceded by # will not reach the server-side script. That can be accessed only by Javascript.
Yes it's true, the server doesn't get the anchor part. However there is a workaround using cookies. You can find it here: http://www.stoimen.com/blog/2009/04/15/read-the-anchor-part-of-the-url-with-php/

how to get share buttons to use the current URL?

<a href="http://www.linkedin.com/shareArticle?url=MY_URL" class="in-share-button" target="_blank">
<img src="my_img" alt="linkedin share button" title="Share on Linked In" /> </a>
This is currently my share button. I want it to share the url that's currently in the address bar, and not a fixed preset url like it does atm.
I found
<?php $url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; echo $url; ?>
what seems to fit my needs. But when I change "MY_URL" with this it just creates a link to the main page of my website.
The URL it SHOULD display looks like "www.myurl.de/#/id_of_a_post".
I feel like the # is the problem. . .
can you provide me any help with this?
You cannot read the hash portion of the URL in your server side code. The part that follows # is never sent to the server by the browser. So if you're trying to tackle this issue with PHP, you won't get the behavior that you're are expecting.
It looks like you're relying on static links to perform the sharing. I can only answer for Google+, but with Google+ you have two options:
Use the Google+ widget rather than a static link and do not specify the HREF parameter:
<div class="g-plusone" data-annotation="none"></div>
<!-- Place this tag after the last +1 button tag. -->
<script type="text/javascript">
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
</script>
When the href is not specified and you do not specify a canonical URL, the widget falls back to default to the URL value that comes from document.location.href, which will be your visitor's current page, including the hash portion of the URL.
Use JavaScript to rewrite the URLs in your links to append your current hash location, for example, lets assume that you placed all your social links into a div with class "sharing" and then you need to modify all the hrefs within that div using jQuery:
var hash = document.location.hash;
// Loop through each link in the sharing div
$('.sharing a').each(function(){
// Append the hash to the end of each already populated URL
$(this).attr('href', $(this).attr('href') + encodeURIComponent('#' + hash));
});
It just worked another way.
My friend created a script that saves the ID of the individual posts:
(function(){
var numbers = document.URL.match(/\d+/g);
if(numbers != null){
$('#right-col').addClass('shown').removeClass('hidden');
$('#left-col').addClass('colPositioning');
$('#right_'+numbers).addClass('shown1');
;}
}());
Afterwards I was able to use:
<img src="img_src">
The trick about it was to replace the # with the "%23". I think it's called encodedURI.
What do you guys think about this solution?
The share might not work exactly the way you think it will. You're using the anchor part of your URL to link to a specific place on your page, and probably using some javascript to then process that and load new or different information, or display/hide other parts of the page, depending on the value of that anchor.
While this works for people who visit your website, it won't work for bots that visit your website (such as the bots used by Facebook and Google+, although I don't know if Linkedin does this as well) which try to get a snippet of information to show as a preview. So while the link itself might work, the preview shown on the website will almost certainly not reflect the contents of the anchored URL.

Removing IDs from HTML elements before saving them to database

I am working on a application which can save user-created HTML templates. Here, the user will have some HTML components at his disposal and would be able to create static HTML pages using those components.
I am auto saving the content of the page using a javascript function.
function saveContent(){
//var getContent=$('#mainWrap').children().removeAttr('id');
var $getContent=$('#mainWrap');
var $finalContent=$getContent.children().removeAttr('id');
var auto="auto";
var pageId = <?php echo $pageId;?>;
var webId = <?php echo $webId;?>;
var userId = <?php echo $userId;?>;
$.ajax({
url:"auto_save.php",
type:"POST",
dataType:"text",
data:"txtComp="+$('#mainWrap').html()+"&auto="+auto+"&pageId="+pageId+"&webId="+webId+"&userId="+userId
});
}
var interval = 1000 * 60 * 0.30; // where X is your every X minutes
setInterval(saveContent,interval);
Issue: I want to to remove the IDs from the HTML components that the user saves, because the IDs are auto generated and not needed when the user publishes the template (on his domain after creation). I have a main wrapper that wraps the entire page called id=mainWrap. If I try to remove the IDs like this $('#mainWrap').children().removeAttr('id'); they are also removed from the current context of the DOM, i.e they are removed from the page where the user is editing his template.
Question: How can I remove the IDs from the HTML elements without affecting the current context of the mainWrap object?
I tried assigning it to another object like this
var $getContent=$('#mainWrap');
var $finalContent=$getContent.children().removeAttr('id');
but still it failed.
Any comments or corrections on whether this is possible? Or am I going about this the wrong way?
Update : The issue is solved to some extent.
Next I want to add the id's back when the user comes back to the edit page.
I get the above saved content using this code
<?php
$sqlEdit = "select revisionContent from tbl_revision where revisionId='".$_SESSION['contentId']."'"; //The query to get the record
$rsEdit = $dbObj->tep_db_query($sqlEdit);//The database object to execute the query
$resEdit = $dbObj->getRecord($rsEdit);
$IdLessContent = $resEdit['revisionContent'];//Variable with the record
?>
Now,I want to use this PHP variable in javascript,so I did this.
<script language="javascript">
var getSavedContent = '<?php echo json_encode($IdLessContent); ?>';
var trimmedCont=($.trim(getSavedContent).slice(1));
//console.log(trimmedCont);
var lengthCont= trimmedCont.length;
var trimmedCont=$.trim(trimmedCont.slice(0,lengthCont-1));
var pageContent=$('<div class="addId">').append(trimmedCont); //Here I tried creating a div dynamically and appending the content to the div.But now I am not able to manipulate or work on this dyamic div and get NULL when I alert saying $('.addId').html();
$('.addId').children().attr('id', 'test'); //I tried doing this but does not work
This is not working.Can you throw some light on it
You can just cycle through the elements in your #mainWrap and remove the id like:
var getContent = $('#mainWrap');
var finalContent = getContent.parent().clone().find('*').removeAttr('id');
Example: http://jsfiddle.net/7m8g4/6/
Security wise you should realize this is a client-side script that is removing the id attributes from the html. There are ways though to manipulate the JavaScript or to bypass it by (for instance) calling the URL in your Ajax request directly with false data.
So you should never rely on your JavaScript only. Make sure your code will not cause problems if for any reason the JavaScript doesn't act as expected. You can do this for instance by searching for id attributes (use a regex) and generate an error message in case there are still some id attributes found. Another way would be to remove them server-side (in PHP) as well if any are found. To achieve this you could do a regex search and replace the matches with empty strings or by making use of substrings. Up to you!
Hope it all makes sense!
EDIT
If you want to add new id attributes back later on you can do something like:
var newContent = $(finalContent).first().wrap('<div class="addId" />');
newContent = $(newContent).parent().find('*').each(function(index, value) {
$(this).attr('id', index);
});
See that in work here.

Get the data from an iframe after form post has completed performing a file upload on target for

I have a form which uses the target attribute to target an iframe when the form is posted which posts to a PHP script. This part is working fine but I need to do something based on several results that the php script will put in the iframe.
What I am thinking of doing is when the PHP script has finished posting it echo's out some hidden input fields that contain various elements, such as the state of the post, whether it succeeded and what the final result was if it was successfully posted.
However, if I did this it would put it into the iframe so then the main web page wouldn't be able to access the hidden input fields.
How would the main web page be able to access these hidden input fields so that the main web page can perform some action, I.e. make a div within the web page show a specific error message or whatever.
The other thing is, once I know how I can get the data from the hidden input field, how would I know when I can go and get the values. I was thinking that when the form is posted via a JavaScript document.forms["myform"].submit() code I could then do a while loop and check to see if another hidden input field status is set to complete and once it says complete I can then get the values from the hidden input field.
I'm not sure if the way I suggested is the right way or doing what I want to achieve or if there is a better way of doing it.
UPDATE
I've tried what #lanzz suggested but it doesn't appear to have worked. Below is what I have tried.
$("iframe#image_upload_frame").on('load', function()
{
var iframeBody = this.contentDocument.body;
var data = $(iframeBody).find("#imageDirectory");
alert("data: " + data);
});
Below is how the iframe is defined
<iframe id="image_upload_frame" name="image_upload_frame"></iframe>
and I am echoing out a hidden input field in the php script that's within the iframe.
echo '<input type="hidden" id="imageDirectory" value="'.$imageDirectory.'" />';
The echo is definetly working as when I see view the iframe source I can see the hidden input however, the alert dialog is never shown as if something isn't working. There are no errors being reported either by the google chrome dev console.
If I understand correctly - you need a value from the iframe in the parent window, once the value is loaded into the iframe. I would add javascript to the iframe calling the parent and executing a function.
In the main frame:
function incomingValue(val) {
alert(val)
}
and somewhere in the generated iframe:
<script type="text/javascript">
parent.incomingValue("Hello world");
</script>
This should work assuming both frame sources share the same domain.
You can use postMessage for cross document communication between an iframe and it's parent.
See:
http://viget.com/extend/using-javascript-postmessage-to-talk-to-iframes
http://javascript.info/tutorial/cross-window-messaging-with-postmessage
Since you're running on the same domain, your main page's Javascript will have no trouble to access the contents of the <iframe> (example uses jQuery, you could rewrite into whatever libs you plan to use):
$('iframe#the-id-of-the-iframe').on('load', function() {
var iframeWin = this.contentWindow;
var iframeBody = this.contentDocument.body;
// access global JS vars defined in the iframe:
var someIframeVariable = iframeWin.globalIframeVariable;
// or, directly access elements in the iframe:
var someIframeElement = $(iframeBody).find('#element-id-inside-iframe');
});
A while ago I wrote a piece of code to upload a picture using some javascript and two iframes. The most important thing for me was to preview the pic. Maybe it will help you:
HTML:
<div id='fakebutton' onclick='select_pic()'>Just a button to select a pic</div>
<iframe src='uploadform.php' name'pic_frame'></iframe>
<iframe src='#' name='target_frame'></iframe>
both the iframes are hidden. The targetframe has no source (or an empty page, if you want to).
uploadform.php contains a form:
<form id='upload_form' action='dosomething.php' method='post' enctype='multipart/form-data' target='target_frame' onsubmit=''>
<input id='realfoto' name='realfoto' type='file' onchange='parent.foto_upload(window.frameElement.id)'>
</form>
and then some javascript:
First of all something to trigger the filebrowser when the user clicks the fake
function select_pic(){
b=window.frames['pic_frame'];
b.document.upload_form.realfoto.click();
}
And then a part to actually upload the pic, triggered by the onchange() in the input element:
function foto_upload(o){
var b=o;
o=getElementById(o);
if(o.contentDocument ) {o = o.contentDocument;}
else if(o.contentWindow ){o = o.contentWindow;}
else{return false;}
if(test_pic(o,b)){ //test if it is really a pic
getObj('foto_tmpdir').value=o.getElementById('tmp_dir').value;
o.getElementById('doctype_nr').value=b;
o.fotoform.submit();
}
else{
return false;}
}
In dosomething.php I perform actions on the uploaded pic (rename, resize etc). And it contains a few lines of javascript:
$a = 'upload was succes';
$b = 'my_image_name';
$c = 'whatever you want to put here';
?>
<script type="text/javascript">
window.top.window.smurf(<?php echo "'$a','$b','$c'" ?>);</script>
<?php
if you create in javascripty a function named smurf(a,b,c) you can pass along whatever you want form the php-script. One of the most important things for me was that I now can pass the filename of the uploaded pic to javascript, and use it to change an image.src for a preview.
Hope you can use something of it.
Your iframe source page should has a javascript call function instead of the hidden field. The function will call the opener window (your main page) and then it do any functionality you want. As blue print look at the following:
//in iframe src.php
<?php
if ($something){
?>
<script>
function doSomethingWithOpenerWindow(){
opener.document.write('hi);
}
doSomethingWithOpenerWindow()
</script>
<?php
}
else{
?>
<script>
function doAnotherSomethingWithOpenerWindow(){
opener.document.write('hi);
}
doAnotherSomethingWithOpenerWindow()
</script>
<?php
}
?>

How to make browser not to refresh full page when it goes to URL?

I tried to understand - is it any method to ask browser not to refresh entire page when user clicks onto . Hash adding method is seen - I need another method, working with links without hashes.
May be any headers should be sent ? Or something another ?
I want to process GET queries returning only the part of HTML (or special js commands), not all page, and process it in AJAX-style.
You can ajaxify your links through jquery. Something like this:
$('a.ajax').click(function(ev){
ev.preventDefault();
var target=$(this).attr('data-target');
var url=$(this).attr('href');
$(target).load(url+' '+target);
}
This can be used in conduction with the following HTML:
<div id="output">
Hello World
<div>
and inside world.html you would need to have:
<div id="output">
Foo bar baz boo
</div>
In theory this should load content of the dif from "world" file into the div inside the first file, but I haven't tried it. I think it's what you need, because the regular link is still there, google will properly index this bypassing ajax and your users will be happy to see part of the page change.
you could make it 'fake' links doing something like this:
<span style="cursor:pointer;" onclick="loadPage('mypagename');">My Link</span>
The function then would be:
function loadPage(pageName){
// do ajax call here using pageName var
}
You cannot prevent navigation when a user clicks a hyperlink with a URL. Using a hash value to navigate or having your hyperlinks invoke JavaScript is generally the way to add navigation inside of a single page.
However, if you're trying to convert an existing page that's not designed this way, you would have to use JavaScript to modify hyperlinks so they invoke Ajax. For example:
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
var oldUrl = links[i].getAttribute('href');
links[i].setAttribute('href', 'javascript:void(0)');
links[i].onclick = (function(url) {
return function() {
// Then you can do your AJAX code here
}
})(oldUrl);
}
I recommend that you don't do something like this, though, and rather create your page with an AJAX design in mind.
Changing the url without using hashes can be achieved with the Html5 History API: http://html5demos.com/history
Not supported by older browser though, so you must always have a fallback.

Categories