Cannot get filename from iframe I post to - javascript

I'm trying to upload an image using jQuery and PHP. I know there are many plugin solutions, but I'm using this. I can upload the file to the server with no problems, but for the life of me I cannot figure out how to get the file name so I can show the image. Is there any way to get the file name from the iframe I post to? Here is the code I am working with:
jquery
$('#file').change(function()
{
var iframe = $('<iframe name="postiframe" id="postiframe" style="display:none" />');
$("body").append(iframe);
var form = $('#form');
form.attr("action", "../hub.php?handler=add_item");
form.attr("method", "post");
form.attr("enctype", "multipart/form-data");
form.attr("encoding", "multipart/form-data");
form.attr("target", "postiframe");
form.attr("file", $('#file').val());
form.submit();
$("#postiframe").load(function()
{
iframeContents=$("#postiframe")[0].contentWindow.document.body.innerHTML;
console.log('added : '+iframeContents);
});
});
The above code outputs nothing other than the "added :" portion. Any help is greatly appreciated :)

You have to echo/print the filename or path from the server after the upload is complete (preferably in text/HTML as you're posting to an iframe) so you can obtain it with Javascript as in your question's code.
iframeContents=$("#postiframe")[0].contentWindow.document.body.innerHTML;
console.log('added : '+iframeContents);
You may as well code a new JS request to fetch the uploaded images through Ajax to a new PHP (echoing JSON for example), but it's unneeded if you want to get just the uploaded file in that form submit.

You can pass some string data from iframe to main window using window.name technique.
Short example of using:
Iframe:
//doing your stuff, when finished store what you need in window.name property
window.name = '{"key1":"mydata1","key2":"mydata2"}'
window.location.href='about:blank';
Main window:
$(iframe).bind('load',function(){
//triggered every time iframe's location is changed
var iframe_data = this.contentWindow.name;
if(!iframe_data.length) {
//it's a first time iframe loaded
return;
}
else{
//iframe location is changed, we're expecting to receive some data
$(this).unbind('load');
console.log($.parseJSON(iframe_data));
//{"key1":"mydata1","key2":"mydata2"}
}
})
It should work even if the iframe placed at another origin (domain).
I didn't tested this code specifically, but it should work, i copypasted it from one of my projects

Related

Linking bookmarklet with site's bookmark [duplicate]

Is it possible to call a javascript function from the URL? I am basically trying to leverage JS methods in a page I don't have access to the source.
Something like: http://www.example.com/mypage.aspx?javascript:printHelloWorld()
I know if you put javascript:alert("Hello World"); into the address bar it will work.
I suspect the answer to this is no but, just wondered if there was a way to do it.
There isn't from a hyperlink, no. Not unless the page has script inside specifically for this and it's checking for some parameter....but for your question, no, there's no built-in support in browsers for this.
There are however bookmarklets you can bookmark to quickly run JavaScript functions from your address bar; not sure if that meets your needs, but it's as close as it gets.
You can use Data URIs.
For example:
data:text/html,<script>alert('hi');</script>
For more information visit: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
Write in address bar
javascript:alert("hi");
Make sure you write in the beginning: javascript:
/test.html#alert('heello')
test.html
<button onClick="eval(document.location.hash.substring(1))">do it</button>
you may also place the followinng
<a href='javascript:alert("hello world!");'>Click me</a>
to your html-code, and when you click on 'Click me' hyperlink, javascript will appear in url-bar and Alert dialog will show
About the window.location.hash property:
Return the anchor part of a URL.
Example 1:
//Assume that the current URL is
var URL = "http://www.example.com/test.htm#part2";
var x = window.location.hash;
//The result of x will be:
x = "#part2"
Exmaple 2:
$(function(){
setTimeout(function(){
var id = document.location.hash;
$(id).click().blur();
}, 200);
})
Example 3:
var hash = "#search" || window.location.hash;
window.location.hash = hash;
switch(hash){
case "#search":
selectPanel("pnlSearch");
break;
case "#advsearch":
case "#admin":
}
Using Eddy's answer worked very well as I had kind of the same problem.
Just call your url with the parameters : "www.mypage.html#myAnchor"
Then, in mypage.html :
$(document).ready(function(){
var hash = window.location.hash;
if(hash.length > 0){
// your action with the hash
}
});
you can use like this situation:
for example, you have a page: http://www.example.com/page.php
then in that page.php, insert this code:
if (!empty($_GET['doaction']) && $_GET['doaction'] == blabla ){
echo '<script>alert("hello");</script>';
}
then, whenever you visit this url: http://www.example.com/page.php?doaction=blabla
then the alert will be automatically called.
Just use:
(function() {
var a = document.createElement("script");
a.type = "text/javascript";
a.src = "http://www.example.com/helloworld.js?" + Math.random();
document.getElementsByTagName("head")[0].appendChild(a)
})();
This basically creates a new JavaScript line in the head of the HTML to load the JavaScript URL you wish on the page itself. This seems more like what you were asking for. You can also change the a.src to the actual code, but for longer functions and stuff it becomes a problem. The source link can also link to a JavaScript file on your computer if targeted that way.
No; because it would make links extremely dangerous.
you can execute javascript from url via events
Ex: www.something.com/home/save?id=12<body onload="alert(1)"></body>
does work if params in url are there.
There is a Chrome extension called Bookmarklet URL (no affiliation). To append a URL with JavaScript, so that the JavaScript command is executed just after loading the webpage, one can use ?bmlet=javascript:
Example: Display an alert box
https://github.com/?bmlet=javascript:alert("Hi");
Example: Enable spell-checking while editing a GitHub README file
[Obviously, a spelling checking extension must be originally available.]
https://github.com/<username>/<repositoryname>/edit/main/README.md?bmlet=javascript:document.getElementById("code-editor").setAttribute("spellcheck","true");
On some pages, it might take some time, as the JavaScript command runs after completely loading the page. Simple commands like alert("Hi"); should run quickly.
I am a student and I have just realized my school blocked JavaScript from the address bar. It works with the "a" tag on a .html file but not on the bar anymore. I am not asking for help, I would just like to share this.
You can do one thing that is you can first open the link www.example.com. Then you can search:
javascript:window.alert("Hello World!")

Script not working when variable url for src

Basically I have some HTML and Javascript designed to get data from a webpage. Using jsfiddle I know that the script with the id myscript does successfully get the link so that it becomes.
<script id="myscript" source="whats in the link">
So that part works but then that is supposed to then be used to load a file and get the data from it which isn't working for some reason.
If I have a normal script tag with the src already set (without the document.getElementById thing in my code) then it successfully loads and displays the wanted data.
But somehow even though the script src is changing to what i want it to be the data isn't being loaded.
<script>
var yqlcallback = function(data) {
var results = data.query.results;
document.write(results.span);
var rating = results.span;
rating = rating.slice(0, -1);
document.write(rating);
};
</script>
<script id="myscript"></script>
<script>
var link = "https://query.yahooapis.com/v1/public/yql?q=select%20content%20from%20html%20where%20url%3D%22http%3A%2F%2Fwww.team-des-fra.fr%2FCoM%2Fbf3.php%3Fp%3Dbj9912%22%20and%20xpath%3D'%2F%2F*%5B%40id%3D%22content%22%5D%2Fdiv%5B3%5D%2Fdiv%2Fspan'&format=json&callback=yqlcallback";
document.getElementById('myscript').setAttribute('src', link);
</script>
Checking the console shows me this error
Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.
This similar question has the reason why this error is thrown
Using innerHTML as adeneo did in his jsFiddle seems to work though.

Write a js script in a div

I am trying to get a script from another website using jQuery then document.write it
here is my code
var url = "https://code.jquery.com/jquery-1.10.2.js";
var dam = $.getScript(url);
document.write(dam);
But this doesn't work!!
all what I get on the page is [object Object]
Can this be achieved without XHR?
jsfiddle
Don't use document.write, it does not do what you think it does. What it does not do is write some data at the end of the document. What it does instead, is pipe data into the current write stream. And if there is no write stream, it will make a new one, resetting the document's content. So calling document.write(dam) means you just wiped your document. document.write is a low level JS function from an earlier era of JavaScript, don't use it.
Instead, you want to use modern DOM manipulation functions, so in jQuery, that's stuff like:
$(document.head).append($("<script>").attr("src", url));
where
$("<script>")
builds a new script element,
$(...).attr("src", url)
sets the "src" attribute to what you need it to be, and:
$(document.head).append(...)
or
$(document.body).append(...)
to get the script loaded into your document. If it's a plain script with src attribute, it can basically go anywhere, and if it's a script with text content that should run, you can only make that happen through document.head.
Although if it's just a script you need to load in and run, you can use getScript, but then you don't need to do anything else, it's just:
var url = "https://code.jquery.com/jquery-1.10.2.js";
jQuery.getScript(url);
Done, jQuery will load the script and execute it. Nothing gets returned.
Of course, the code you're showing is loading jQuery, using jQuery, so that's kind of super-odd. If you just want to load jQuery on your page, obviously you just use HTML:
<!doctype html>
<html>
<head>
...
</head>
<body>
...
<script src="http://https://code.jquery.com/jquery-1.10.2.js"></script>
</body>
</html>
with the script load at the end so the script load doesn't block your page. And then finally: why on earth are we loading jQuery version 1.x instead of 2.x? (if you need to support IE8: that's not even supported by Microsoft anymore, so you probably don't need to).
And finally, if we don't want to load the script, but we really just want its content, as plain text, there's only a million answers on Stackoverflow already that tell you how to do that. With jQuery, that's:
$.get("http://https://code.jquery.com/jquery-1.10.2.js", function(data) {
$(document.body).append($("div").text(data));
});
But you knew that already because that's been asked countless times on Stackoverflow and you remembered to search the site as per the how to ask instructions before asking your question, right?
executing the script on the page is not my goal!. I want to get the
script content and put it a div (USING JAVASCRIPT - NO XHR) , is that
possible ?
Try utilizing an <iframe> element
<div>
<iframe width="500" height="250" src="https://code.jquery.com/jquery-1.10.2.js">
</iframe>
</div>
jsfiddle http://jsfiddle.net/snygv469/3/
Make it easier... use my fiddle
http://jsfiddle.net/wwwfzya7/1/
I used javascript to create an HTML element
var url = "https://code.jquery.com/jquery-1.10.2.js";
var script = document.createElement("SCRIPT"); //creates: <script></script>
script.src = url; //creates: <script src="long_jquery_url.js"></script>
document.body.appendChild(script); //adds the javascript-object/html-element to the page.!!!
Use this way, it can fix your problems.
$.get( "https://code.jquery.com/jquery-1.10.2.js", function( data ) {
alert(data);
});
You can try adding
<script src="http://code.jquery.com/jquery-1.8.3.min.js" ></script>
Then an AJAX call, but it pulls data from CACHE. It looks like an AJAX but when <script> is added file goes in cache, then read from cache in the ajax. In cases where it is not stored in cache read it using normal AJAX.
jQuery.cachedScript = function(url, options) {
// Allow user to set any option except for dataType, cache, and url
options = $.extend(options || {}, {
dataType: "text",
cache: true,
url: url
});
// Use $.ajax() since it is more flexible than $.getScript
// Return the jqXHR object so we can chain callbacks
return jQuery.ajax(options);
};
$(document).on('ready', function() {
// Usage
$.cachedScript("http://code.jquery.com/jquery-1.8.3.min.js").done(function(script, textStatus) {
console.log(script);
});
});
Normal Solution
If you are ready to use AJAX look at this fiddle
How to fetch content of remote file and paste it on your document and execute that js code
I guess you want to get content written on remote file and want to write that content in your HTML. to do this you can use load() function.
To do this follow the following steps:
1. Create a file index.html Write the following code in it:
<pre id="remote_script"></pre>
<script>
$(document).ready(function() {
//var url = "https://code.jquery.com/jquery-1.10.2.js";
var url = "remote_script.html";/* For testing*/
$('#remote_script').load(url,function(){
eval($('#remote_script').text()); /* to execute the code pasted in #remote_script*/
});
});
</script>
2. Create another file remote_script.html for testing write alert('a'); in it without any <script> tag and run the above code.

Using AJAX to pass a generated image from PHP back to javascript

I have a php file generating a diagram as an image - this is working fine
This php file has to communicate with javascript (via ajax) to load this image in the html
Initially I got it working by placing this in the javascript:
document.getElementById("img3").src="ajax.php?area=" +encodeURIComponent(area);
where img3 is the image in the html and ajax.php is the php file generating the image
The problem with this code however is there are a few lines after the code above executing before the image is loaded - a timing problem.
Changed javascript/ajax code to:
ar = new XMLHttpRequest();
if(ar.readyState == 4 || ar.readyState == 0)
{
ar.open("GET", "ajax.php?area=" +encodeURIComponent(area), true);
ar.send(null);
ar.onreadystatechange = function()
{
if(ar.readyState == 4)
{
document.getElementById("img3").src = ar.response;
}// end if
}// end function
}// end if
Was with the hope I could place my lines of code inside the if(ar.readyState == 4) block which will solve the timing problem. But the image isn't loading. Any ideas?
I understand that you don't really care how the image is loaded (using src or ajax) but what you want is to execute a piece of code after an image has loaded.
There are several (some better than others) ways of checking if an image is loaded. This tread covers some of them.
For instance you could use the onload event to trigger a piece of code
document.getElementById("img").onload = function() {
//do the code which has to be executed after loading the image.
}
They describe some problems with the event not firing when the image loads from cache, but a browser (almost) never caches a .php file with get parameters. You should check if caching is an issue for your project, based on what i understand from your project i think it is not a problem.
They suggest other options which are interesting to investigate. There is one i find interesting where they suggest using imageloaded. That solution looks very solid.

How can I let users browse there computer to choose a background image in HTML JAVASCRIPT

I'm trying to allow users to browse their documents and choose a picture to set as a background image. I have already found out how a user can change the background image using a URL. Please find the demo below:
DEMO: http://goo.gl/253IN
Username: demo
Password: demo1
I dont know how to get it to work with the
File Field
I have found the following Example which I would like to use. Found question here
JavaScript:
$(switchBackground);
var oFReader = new FileReader(),
rFilter = /^(?:image\/bmp|image\/cis\-cod|image\/gif|image\/ief|image\/jpeg|image\/jpeg|image\/jpeg|image\/pipeg|image\/png|image\/svg\+xml|image\/tiff|image\/x\-cmu\-raster|image\/x\-cmx|image\/x\-icon|image\/x\-portable\-anymap|image\/x\-portable\-bitmap|image\/x\-portable\-graymap|image\/x\-portable\-pixmap|image\/x\-rgb|image\/x\-xbitmap|image\/x\-xpixmap|image\/x\-xwindowdump)$/i;
oFReader.onload = function(oFREvent) {
localStorage.setItem('b', oFREvent.target.result);
switchBackground();
};
function switchBackground() {
$('body').css('background-image', "url(" + localStorage.getItem('b') + ')');
}
function loadImageFile(testEl) {
if (! testEl.files.length) { return; }
var oFile = testEl.files[0];
if (!rFilter.test(oFile.type)) { alert("You must select a valid image file!"); return; }
oFReader.readAsDataURL(oFile);
}
HTML:
<input id="test" type="file" onchange="loadImageFile(this)" />
However I cant get it to work with my current code (Please refer to demo)
Thanks in advance
PS I am not an expert (yet :D) on HTML and Javascrpit so I will not be able to understand really complex code
In short, you cannot use the file input in this way. JavaScript does not have access to the users direct machine for security reasons. This input simply allows a file to be passed across the web stream in the body of an HTTP POST request.
To accomplish what you are wanting, you would have to upload the file server side using a server side language such as PHP or ASP.NET. You could then save it off and store it, allowing it to be displayed as the users background whenever they visited.
not impossible at all!
you can actually add this functionality to you website using this plugin
https://github.com/CybrSys/custom-background.js

Categories

Resources