Echo the src value of an iframe on a page - javascript

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="http://test.com" />
How I can use PHP to get the src which is "http:/test.com" ... so it will be like that:
$getiframesrc=THE_CODE_WHICH_I_WANT_SOMEONE_TO_TELL_ME_ABOUT_IT;
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 :
"THE_CODE_WHICH_I_WANT_SOMEONE_TO_TELL_ME_ABOUT_IT" .
EDIT: $getiframesrc will be in index.php too!
And thanks :-)

you can use ajax and jquery to get the src value then send it to the php file
Jquery
$(document).ready(function(){
var vidsrc = $("#iframeid").attr("src");
$.post( "index.php", { videosource: vidsrc });
});
index.php
if (isset($_POST["videosource"]))
{
$videosource = $_POST["videosource"];
// code to be excuted
}

Here's a working example -- and make sure you close your <iframe> tag.
$('button').click(function(){
var src = $('iframe').attr('src');
alert( src );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button>Read iframe src</button>
<iframe src="http://test.com"></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.
EDIT:
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.

Firstly, thank you very much #gibberish ( gibberish ) for your answer, it's the best answer for me and I'm using it now :-) .
I figured out how to do that with PHP (thanks for #gibberish to help, because his example helped me.) - But sorry :/ I can't say how I did that because it's very hard coded (everything is manual in that) ... so I will simplify it and post the answer :-)
Next to the #gibberish answer, we can use PHP GET variable and set the iFrame src with it.
Example:
PHP Part in index.php :
<?php
$iframesrc=$_GET['iframesrc'];
?>
HTML Part in index.php :
<iframe src=<?php echo $iframesrc; ?>></iframe>
And then we can access http://Mysite.tld/index.php?iframesrc=http://test.com ;)
So now, I can code well - like that:
if($iframesrc !=="http://test.com")
{
//code
}

Related

Insert HTML Content from URL into HTML (form, div, iframe, ...)

I want to display the result of this URL
http://api.openweathermap.org/data/2.5/weather?q=Berlin,de&mode=html&appid=...1
which looks like
https://i.stack.imgur.com/WWRoD.png
how can I insert the HTML content from the URL directly into an iframe or div?
Thanks!
If you already are able to get that response html, all you need to do is insert it onto the page
document.getElementById('mydiv').innerHTML = "<p>some html</p>"
This could easily be achieved by PHP.
<?php
echo file_get_contents("ENTER URL HERE");
?>
You could do this via JavaScript, but that would require making an AJAX request to get the HTML and then inserting it into the DOM. I don't think that this would be the best method as the page would have already loaded without the code and then asynchronously adding it to the page. Depending on how it is meant to be viewed, I think this would lead to a poorer UX.
Edit
To download the HTML asynchronously, you should use .get(), instead of .load().
$.get("URL", function(data) {
$(".mydiv").html(data);
});

jQuery.ajax replace PHP code

I'm trying to update a REST search result with ajax to not reload a new page.
right now search result is shown within:
<div id="searchtable"><?php include 'hotels/hotelList.php';?></div>
On click on button I want to reload this div element so it includes a new php file.
Button:
<button onclick="myFunction()">LOAD</button><br /><br />
jQuery
<script>
function myFunction() {
$.get( "/hotels/hotelSortBy.php" );
$('#searchtable').replaceWith('<?php include 'hotels/hotelSortBy.php';? >');
}
</script>
I'm not able to replace the div element "searchable" - with replaceWith - Am I doing this right ?
There's no need for inline PHP if you're using AJAX. Try using jQuery's .load AJAX method:
function myFunction() {
$('#searchtable').load('/hotels/hotelSortBy.php');
}
Note that this is slightly different than .replaceWith -- using .load will preserve #searchtable and put the new content inside of it, rather than replacing it.
You're misunderstanding a key element here. Your javascript is running on the client side, while the php runs on the server side (at least usually). Javascript doesn't interpret php and php doesn't interpret javascript either (except json). What you probably want to do is an ajax request to call the url that serve this php file, so that your webserver interpret php and return a response. Check http://api.jquery.com/jquery.ajax/ probably?
Try using .html instead of replaceWith.
So it would look like
function myFunction(){
$('#searchtable').html('<? php include 'hotels/hotelSortBy.php'; ?>');
}

pictures with Javascript from array

EDIT: I have followed the advice of Happy and Bart Friederichs and it has been really helpful. Instead of using php i am using javascript and the code is now working, but i still have an issue. When I click the button on the page it displays the pic that i want but the button disappears, so i cant cycle though the rest of the pictures in the array. What going on? Any help would be appreciated.
<html>
<head>
<script type="text/javascript">
var picArray=["images.jpg","customLogo.gif.png"];
var count=0;
function changePic(){
document.write("<img src='"+ picArray[count] +"' />");
count++;
}
</script>
</head>
<body>
<button type="button" onclick="changePic()">Click Me!</button>
</body>
</html>
Your changePic() function is a PHP function however when you call onclick="changePic()" you are using HTML to call a Javascript function. If you looked at your debug window in your browser you would see an error saying that changePic does not exist.
You can not use html's onClick to call a PHP, not without either redirecting or calling 'wrapper' function in JS that loads your PHP file with arguments via AJAX and so forth.
You have a few options here.. either put your images into a Javascript array and use the onclick call to grab them from that, if your doing that, you do not even need your iframe you can just print the image directly to the page using document.write. Or, why not just set the source of the iframe to your PHP script with an argument for the array index. So where you have
src=$picArray[count]
Change to
src=whatever.php?image=1
For example. This way would only need to render the iframe once rather than on every click like you are attempting to know, you would just be changing the iframe content.
There are a heap of ways to do what you are trying, let me know if either of the above suggestions work for you.
You need to use ajax to handle the onClick event, this in turn would run a PHP page in the background which could return it a filenmae.
Then ajax / jQuery would change the actual pic
Here is a tutorial covering ajax with php:
http://www.tizag.com/ajaxTutorial/ajaxxmlhttprequest.php
Alternatively you can output all the filenames to a java script array:
echo '<script> var picarray = array() ;';
foreach($arrayPic as $pic) ...
Then just access it using js

CakePHP: Send current model ID to another controller via AJAX

So I'm in my edit view... let's says it's posts/edit/1
That page loads some Javascript which makes a $.get call that pulls data from a different action on the same controller (posts/foo).
How can I simply send the current model's ID to AJAX, and on to the other controller?
In this case, both actions are in the same controller, but I'm not sure that helps in this case.
if you are using jquery you can have something like this
$(document).ready(function(){
//ajax call here
});
The thing is that once your document has loaded you just send this id to the other controller.
I hope that helps
If you only need to get the Post ID from your edit view, this is the variable you need:
$this->Form->fields['Post.id']
If its not "Post", just replace it with the model name you are using and trying to get the ID for.
UPDATED: Based on the clarification: you are right; for what you are trying to do, you need to generate the link or just the unique ID in a script tag, and then somehow use that variable in your included script. Take a look at how I did it for a CakePHP plugin. A quick summary:
Include the JS files as you would normally do
Create a variable in a script tag in the controller
Use that variable in the included JS files
Something like this:
<script type="text/javascript">
id = '<?php echo $this->Form->fields['Post.id'] ?>;
</script>
and then use this id variable in your included Javascript file.

Getting content of a script file using Javascript

I have the following script element in my web page:
<script src="default.js" type="text/javascript"></script>
Using JavaScript, I want to be able to retrieve the content of the script file. I know I could use an ajax request to get the data but then I am getting something from the server that I already have locally.
So what I would prefer to do is retrieve the content from the DOM (if that's possible) or something that has the same result.
Cheers
Anthony
UPDATE
I was trying to simplify the question, maybe a bad a idea, I thought this way would cause less questions.
The real situation I have is as follows, I actually have
<script type="text/html" class="jq-ItemTemplate_Approval">
...
html template that is going to be consumed by jQuery and jTemplate
...
</script>
Now this works fine but it means each time the page loads I have to send down the template as part of the HTML of the main page. So my plan was to do the following:
<script src="template.html" type="text/html"></script>
This would mean that the browser would cache the content of template.html and I would not have to send it down each time. But to do this I need to be able to get the content from the file.
Also in this case, as far as I know, requesting the content via ajax isn't going to help all that much because it has to go back to the server to get the content anyway.
If I understand you correctly, you don't want to use Ajax to load an html template text, but rather have it loaded with the rest of the page. If you control the server side, you can always include the template text in an invisible div tag that you then reference from Javascript:
<div id="template" style="display:none;">
...template text...
</div>
<script>
// pops up the template text.
alert(document.getElementById("template").innerHTML);
</script>
If you are just looking for to load the template so that you can have it cached, you can put the contents in a variable like this:
<script>
var template = "template text..";
</script>
or you can load it using ajax and store the template in a variable so it is accessible. It's pretty trivial in jquery:
var template;
$.get("template.html", function(data){
template = data;
});
unless you load a script as literal text in the page, it does not exist as text. It is interpreted by the browser and melded into the runtime, with any other scripts.
If you want the source you have to fetch it again,if with Ajax get the responseText.
It will come from the browser cache, and doesn't have to be downloaded again.
I think what you want to do is to assign a variable inside template.js. Then you have the variable available for use wherever you want in jquery. Something like:
var tpl = "<div> ... </div>"
Wouldn't this be a simpler solution to your problem? We do this in Ext JS. I think this will work for you in jQuery.
You could get the attribute of the src of the script and then use XHR to get the contents of the JS file. It's a much cleaner way of doing it IMO. e.g.:-
if(window.XMLHttpRequest) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.status == 200 && xhr.readyState == 4) {
var sourceCode = xhr.responseText;
alert('The source code is:-\n'+sourceCode);
}
}
xhr.open("GET",document.getElementById('scriptID').src,true);
xhr.send(null);
}
Using an iFrame & HTML5 Local Storage
Save the templates for rendering later...
not stoked about the iFrame, but it seems to be working pretty good (haven't ran performance tests yet)
Put the iFrame on the page you want the template on (index.html)
<html>
<head>
<iframe src="mustache.Users.html" onload="this.remove();" class="hidden" id="users_template"></iframe>
</head>
</html>
Make sure the src attribute is set
hide the element until you can get rid of it after it loads
Put this body wrapper around your template (mustache.Users.html)
(don't worry it won't show up in the template)
<body onload="localStorage.setItem('users_template',this.document.body.innerHTML);">
<ul class="list-group" id="users" >
{{#users}}<li>{{name}}</li>{{/users}}
</ul>
</body>
replace 'users_template' with whatever name for your variable
the 'onload' attribute saves the template into localStorage during load
Now You can access your templates from anywhere
localStorage.getItem('users_template')
OR
window.localStorage.getItem('users_template')
What is in the JavaScript file? If it's actual code, you can run functions and reference variables in there just like you had cut and paste them into the webpage. You'll want to put the include line above any script blocks that reference it.
Is this what your looking to accomplish?
Why not use Ajax (well Ajah because its html :-))?
when the server is set up correctly and no no-cache or past expires headers are sent, the browser will cache it.
The way that most JavaScript import files work is they include a script, that immediately calls a function with a parameter of certain text, or of another function. To better illustrate, say you have your main index.html file, set it up like this:
<html>
<head>
</head>
<body>
<script>
let modules = {};
function started(moduleName, srcTxt) {
modules[moduleName] = (srcTxt) //or something similar
}
</script>
<!--now you can include other script tags, and any script tags that will be included, their source can be gotten (if set up right, see later)-->
<script src="someOtherFile.js"></script>
</body>
</html>
now make that other file, someOtherFile.js, and right away when its loaded, simply call that "started" function which should already be declared in the scope, and when thats done, then whatever text is passed, from the file, is stored in the main index.html file. You can even stringify an entire function and put it in, for example:
started("superModule", (function() {
/*
<?myCustomTemplateLanguage
<div>
{something}Entire Javascript / html template file goes here!!{/something}
</div>
?>
*/
}).toString());
now you can access the inner content of the function, and get all the text in between the comments, or better yet, then do other parsing etc, or make some other kind of parsing identifiers at the beginning and end of the comments, as shown above, and get all text in between those

Categories

Resources