pictures with Javascript from array - javascript

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

Related

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="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
}

How to pass element ID variable to jQuery load function

I am fairly new to Jquery and HTML so please bear with me. I have my index.html with a call to jquery-1.9.1.min.js and I want to create a script that would load an outside html file. Index.html is a fairly long file so I want to break up the section for cleaner code and make it easier to modify.
<html class="no-js">
<main>
<section id="testLoad"></section>
</main>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.9.1.min.js"><\/script>')</script>
<script>$("#testLoad").load("test.html #part-1"); </script>
</body>
</html>
As you can see from the code above it loads the html file fine. What I want to do is set "#part-1" as a variable so that I can call the load script again but call a different ID from another part of the file.
I would also be open to different methods aside from this load function. All I need is to call an external html file (there are about 30 different sections) so it can display that sections data. If I do it this way is there a way to create a header file so that all of these section can have access to the same style sheet?
You'd put your load function inside a named function and pass in an argument:
function loadStuff(divId) {
$("#testLoad").load("test.html #" + divId + '');
}
In your event handler you'd call it:
$(document).ready(function() {
loadStuff('someId');
});
You could also pass in the target ID in a similar manner.
As others have pointed out, this isn't the ideal way to do what's essentially client-side templating.
It seems like you want to be able to combine multiple different "partial" html files, and for this I would recommend you look into Angular which excels at exactly this.
Not sure why you are loading the JQuery js file the way you are. That really doesn't look safe.
Another thing you can do is create an "iffy" as some people call it where it is a script that is automatically called when the page is loaded.
<script>
(function (){
//code goes here
}())
</script>
This code will run when that page is loaded.

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'; ?>');
}

How do I get the original innerHTML source without the Javascript generated contents?

Is it possible to get in some way the original HTML source without the changes made by the processed Javascript? For example, if I do:
<div id="test">
<script type="text/javascript">document.write("hello");</script>
</div>
If I do:
alert(document.getElementById('test').innerHTML);
it shows:
<script type="text/javascript">document.write("hello");</script>hello
In simple terms, I would like the alert to show only:
<script type="text/javascript">document.write("hello");</script>
without the final hello (the result of the processed script).
I don't think there's a simple solution to just "grab original source" as it'll have to be something that's supplied by the browser. But, if you are only interested in doing this for a section of the page, then I have a workaround for you.
You can wrap the section of interest inside a "frozen" script:
<script id="frozen" type="text/x-frozen-html">
The type attribute I just made up, but it will force the browser to ignore everything inside it. You then add another script tag (proper javascript this time) immediately after this one - the "thawing" script. This thawing script will get the frozen script by ID, grab the text inside it, and do a document.write to add the actual contents to the page. Whenever you need the original source, it's still captured as text inside the frozen script.
And there you have it. The downside is that I wouldn't use this for the whole page... (SEO, syntax highlighting, performance...) but it's quite acceptable if you have a special requirement on part of a page.
Edit: Here is some sample code. Also, as #FlashXSFX correctly pointed out, any script tags within the frozen script will need to be escaped. So in this simple example, I'll make up a <x-script> tag for this purpose.
<script id="frozen" type="text/x-frozen-html">
<div id="test">
<x-script type="text/javascript">document.write("hello");</x-script>
</div>
</script>
<script type="text/javascript">
// Grab contents of frozen script and replace `x-script` with `script`
function getSource() {
return document.getElementById("frozen")
.innerHTML.replace(/x-script/gi, "script");
}
// Write it to the document so it actually executes
document.write(getSource());
</script>
Now whenever you need the source:
alert(getSource());
See the demo: http://jsbin.com/uyica3/edit
A simple way is to fetch it form the server again. It will be in the cache most probably. Here is my solution using jQuery.get(). It takes the original uri of the page and loads the data with an ajax call:
$.get(document.location.href, function(data,status,jq) {console.log(data);})
This will print the original code without any javascript. It does not do any error handling!
If don't want to use jQuery to fetch the source, consult the answer to this question: How to make an ajax call without jquery?
Could you send an Ajax request to the same page you're currently on and use the result as your original HTML? This is foolproof given the right conditions, since you are literally getting the original HTML document. However, this won't work if the page changes on every request (with dynamic content), or if, for whatever reason, you cannot make a request to that specific page.
Brute force approach
var orig = document.getElementById("test").innerHTML;
alert(orig.replace(/<\/script>[.\n\r]*.*/i,"</script>"));
EDIT:
This could be better
var orig = document.getElementById("test").innerHTML + "<<>>";
alert(orig.replace( /<\/script>[^(<<>>)]+<<>>/i, "<\/script>"));
If you override document.write to add some identifiers at the beginning and end of everything written to the document by the script, you will be able to remove those writes with a regular expression.
Here's what I came up with:
<script type="text/javascript" language="javascript">
var docWrite = document.write;
document.write = myDocWrite;
function myDocWrite(wrt) {
docWrite.apply(document, ['<!--docwrite-->' + wrt + '<!--/docwrite-->']);
}
</script>
Added your example somewhere in the page after the initial script:
<div id="test">
<script type="text/javascript"> document.write("hello");</script>
</div>
Then I used this to alert what was inside:
var regEx = /<!--docwrite-->(.*?)<!--\/docwrite-->/gm;
alert(document.getElementById('test').innerHTML.replace(regEx, ''));
If you want the pristine document, you'll need to fetch it again. There's no way around that. If it weren't for the document.write() (or similar code that would run during the load process) you could load the original document's innerHTML into memory on load/domready, before you modify it.
I can't think of a solution that would work the way you're asking. The only code that Javascript has access to is via the DOM, which only contains the result after the page has been processed.
The closest I can think of to achieve what you want is to use Ajax to download a fresh copy of the raw HTML for your page into a Javascript string, at which point since it's a string you can do whatever you like with it, including displaying it in an alert box.
A tricky way is using <style> tag for template. So that you do not need rename x-script any more.
console.log(document.getElementById('test').innerHTML);
<style id="test" type="text/html+template">
<script type="text/javascript">document.write("hello");</script>
</style>
But I do not like this ugly solution.
I think you want to traverse the DOM nodes:
var childNodes = document.getElementById('test').childNodes, i, output = [];
for (i = 0; i < childNodes.length; i++)
if (childNodes[i].nodeName == "SCRIPT")
output.push(childNodes[i].innerHTML);
return output.join('');

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