protld protld - 3 months ago 12
Javascript Question

Echo the src value of an iframe on a page

If I have a file called 'index.php' and this file contains a lot of HTML lines...

Also (index.php) have this iframe:

<iframe src="" />

How I can use PHP to get the
which is "http:/" ... so it will be like that:


And I can easily echo the src of the iFrame by
echo $getiframesrc;

For example: If I want to make a browser using PHP, I want the URL Address Box's text to be the value of the iframe src (THIS IS ONLY AN EXAMPLE!!!)

So, please guys tell me what should be :


will be in

And thanks :-)


Here's a working example -- and make sure you close your <iframe> tag.

  var src = $('iframe').attr('src');
  alert( src );
<script src=""></script>

<button>Read iframe src</button>

<iframe src=""></iframe>

To re-use the src variable elsewhere on the page, just declare it outside the $('button').click(function() function -- or even outside the $(document).ready() fn.


To get the variable data to PHP... By the time the javascript runs, the DOM has been rendered. PHP has finished execution and will not run again on that page.

So, what to do? How to get the variable into PHP? You have two choices:

(1) Use a form - When submitting a form, the data is sent to the PHP file specified in the action= attribute on the <form> opening tag:

<form action="your_secondary_php_file.php" method="post">

Downside to a form is that user is navigated away from the page, or (at the very least) the page is refreshed.

(2) Use AJAX. AJAX (very simple, not to worry) will send your data to a back-end PHP file, the PHP file can do something with that data, and then it can (optionally) send new data/HTML/text/whatever back to the AJAX code block.

Advantage of using AJAX - will not refresh or move away from the current page. All user-entered data remains as is, and you can pro-grammatically receive data back from the PHP side and dynamically update the page with the new data. Magic by another name.

This answer contains some simple examples of AJAX.