How to capture the refresh inside of an iframe from parent document? - javascript

Here's the case:
We have a file upload page. We didn't want to reload the page once the upload is done, so we put the form inside of an iframe. The form inside of an iframe posts to itself and returns json when it's done. How can we capture that response? When upload is done, the iframe reloads, so in other words, how do we capture when the iframe is reloaded?
Assume these:
we cannot print/return anything except the json object (so no js code to call the function in a parent document.)
we cannot use ajax since you cannot post files using ajax
we cannot append javascript code inside of iframe, because once the form inside of iframe is submitted, the page gets reloaded and we lose the appended js code.
Any ideas?
UPDATE - Seems like the solution is super simple (found it somewhere online):
<iframe onload="alert(window['upload_iframe'].document.body.innerHTML);" ...></iframe>
This way, it will fire the alert whenever page inside of an iframe is reloaded. Now it's just matter of differentiating JSON object from HTML code, which is pretty simple. Thanks for everyone for a great advises!

Have you tried appending an "onload" listener to the iframe element to see if when the iframe source is changed it's triggered? That might be a solution. If it doesn't work, then I don't think you have a choice but to execute a top level function from the iframe result.
update
Since you don't have control over the response from the servlet, perhaps you could build a PHP median that communicates with the servlet and takes the raw json it gets and then returns what it needs to execute a parent window javscript function and passing the json to that function.
This way you control the output.

You could check whether the content of the iFrame has changed by performing a timed check of the inner text of the iFrame document against whatever it was last time you checked ( or a hash of it if the document is large ) and then once it has changed you could try parsing the content as JSON to check it is the expected response.
Alternately you could use AJAX to check whether the upload has completed on the server side and once the server confirms that it has finished uploading you can then check the iFrame content.

Related

What happens if I use Ajax to update a single element but return entire html code in the response text?

I'm working on a website and use Ajax to update the body by id name ('mbody'). The website is working as intended but then I realized, I was returning entire page data in the responseText and updating 'mbody' with this response.
Keep in mind, the responseText does include an 'mbody' id name of its own for body.
What I don't understand is, why wasn't the website messed up? I was sticking a copy of the entire page inside an already copy of the page that's in DOM. I have since changed the Ajax update from 'mbody'.innerHTML, to an HTML tag update, since I was returning the whole page.
In case you're wondering if it's necessary to return the whole page, the answer is yes, because things change on the page from top to bottom, from screen to screen so I prefer to just return entire HTML.
So, did Ajax realize I had an 'mbody' inside the responseText and automatically just updated that part with current DOM 'mbody', or did it really place a new html page source in 'mbody' that was already in DOM?
I just want to understand the behavior of Ajax in that situation. Again, my website was perfect even when I was returning entire html source for just the body part.
// the response is returning an html page, while mbody is the current
//DOM body tag's ID
mbody.innerHTML = this.responseText;
//i later set the response to update the entire html; pseudo example
htmltag.innerHTML = this.responseText;
The website function was perfect either way, but sticking a whole page update in the body of the current, I just don't see how that didn't cause issues or destroy the layout or something.
I'm working on a website and use Ajax to update the body by id name
('mbody'). The website is working as intended but then I realized, I
was returning entire page data in the responseText and updating
'mbody' with this response.
It will be easier to debug later (and also less network traffic) if your server side code returned only the values to be updated. Using JSON could also provide less headache because it has it's own format that can easily be accessed by the Javascript without any additional work on a format protocol.
In terms of this part:
In case you're wondering if it's necessary to return the whole page,
the answer is yes, because things change on the page from top to
bottom, from screen to screen so I prefer to just return entire HTML.
You can save the "scroll y position" of the page, before the ajax call, and then after the re-rendering restore that scroll y. But none of this is necessary if you simply only change those parts of the dom that need changing, as opposed to all of it.

Get HTML from a hidden portion of code in a page

The title is a little confusing so let me explain better what the problem I'm having is.
I need to extract a certain portion of HTML out of a page. This portion of code is inside of a div that "on page load" is hidden by default. You have to click on that div in order to make that portion of code appear.
Now, I need to get this code with a javascript/jquery script with either pure AJAX request to the page or YQL but the problem is: How do I "simulate" the click on that div?
How can I make that div toggle just with the code in order to access the code inside of it?
By the way, the request is from the same domain so there's no problem with cross-domain AJAX.
Thank you!
You can use Jquery .click
$("#Id_Of_the_Div_you_want_to_click").click();
As far as my understanding is if you do
$('#hiddenElementID').html() will return the contents of it or even $('#hiddenElementID').text() if its hidden or not.
But if you really must simulate a click then do $('#hiddenElementID').click()
And to toggle use your own function and do $('#hiddenElementID').hide() and $('#hiddenElementID').show()
Or use $('#hiddenElementID').toggle()
http://api.jquery.com/toggle/
Maybe you should try on Ajax success:event
function(data){
//Convert Data to jQuery Object
var element = $(data);
element.find('#HiddenDiv').show();
}
Because manipulating DOM Element's triggering Fake Event's is a bad idea.
You can simulate click events like so:
$("#div").click()
It sounds to me like you're trying to get data from another page. The data is compiled after a click event. You could try the following:
AJAX get the page with the required data
Render the page into a hidded iframe within your page
Simulate click events on the nested page to produce data
Access the bits you want and discard the iframe contents.
If I get some time later I'll try it out for myself and see if it can be done.

Updating value from servlet with pubnub and jquery/javascript during page load

I am new to javascript and the whole front-end side of development.
Here is what I am using:
Java servlet running on Tomcat7
twitter-bootstrap for the layout/theme
Pubnub to keep track of how many times a form is submitted
Javascript/jquery to display this value on a webpage.
I have added the PUBNUB.subscribe callback which updates the value on the webpage just fine. However, when I first load the webpage, I don't know what value I should display.
Here is what I did to overcome this issue:
I added a method to the servlet that, when passed in the correct parameter in a POST request, it will send out a pubnub message with the amount to be displayed which is working fine.
Next, I tried to call a POST request using jquery like this:
$.post("../servlets/theservlet",
{
update : "true"
});
I tried placing that inside a $(window).load function but when I loaded the webpage, it did not do what I expected.
I expected it to do the POST after everything was loaded, which would cause the pubnub message to be published from the servlet, which would activate the callback method in the PUBNUB.subscribe function. However, the value didn't change, it stayed as the placeholder that is hardcoded in the html.
Currently, I am now calling setTimeout("updateUses()", 1500); from within the $(window).load function. updateUses() is the exact same $.post call I showed earlier.
Now when I load the page, the placeholder value is there for a little bit (seems longer than 1.5ms) and then it is updated to the correct value. If I remove the setTimeout and just call updateUses() directly, then nothing happens again.
What do I need to change so that it loads the value instantly (or at least without a noticeable delay)?
If the page builder is JSP and what I have just read is correct then you should be able to do something like this:
RequestDispatcher rd=application.getRequestDispatcher("path/to/pubnub/servlet");
rd.include(request,response);
If you choose to stick with the ajax approach then the javascript should look something like this:
$(function(){
$.post("path/to/pubnub/servlet", {update:"true"}, function(response){
//do whatever is necessary with the response here, eg.
//$("#myElementId").html(response);
});
});
The $(function(){...}) wrapper ensures the code inside it is executed at the earliest opportunity after the DOM becomes ready. Hence no need for a timeout. jQuery is typically written inside such a wrapper.

How to execute a javascript before dom is ready?

I need to execute a javascript before the page is start to load? how can i do it? Atfirst my script should execute, after completion of script, if i need i should load the page else i shouln't load it. For example if my script redirect to another page i shouldnot load the current page else i should load it.
Do it server side ...
The logic you present, seems to fit better at the server side, if you really want to avoid the loading of the page completely..
simply write your script in the script tag as a first element in body tag:
-- updated --
for hiding other page elements, use div with full width and height, if you want to show the page, hide the div, that will fix the problem
You can't run a script before the page loads (without messing up the document type), but you can put the script early in the page, i.e. in the head section.
You can't stop the page from loading until your script has finished. The page will continue to load in the background, but it will not render until the script has finished.
If you do a redirect in your script, the page will stop loading, but what's already loaded will render while waiting for the new response to arrive.
Script tags are execute as soon as they are encountered. Just put your script tag early, and then use a redirect if your condition is true. Hooking the window.onload event handler is how you get Javascript to trigger on load.
Is it possible for you to serve a page initially which contains merely the JavaScript which you need to execute within an HTML document? You can then request the page you want based on the result of the JavaScript.
You could use the jQuery load() method to load a part of a page conditionally, which is not running script before the DOM is ready, but may achieve what you want to do.

How to preload the html in a javascript var

I have a website that I'm working on. I'm using jquery to animate and display content. This content is stored in vars. I need to know how to load the content before displaying it.
For clarification, you click a link, a "loading..." window fades in, and once it loads everything, it fades out and fades in the loaded content that is stored in vars.
Thank you
Are you looking for how to request HTML content via AJAX, know when it is finished, and then insert it into the DOM? If so, jQuery's load method may be what you're after.
Steve
AJAX event will not tell you how many percent was loaded, in fact, in most cases, it has no idea how long is the response will be. But it will inform you when the response is completed, or error occured.
Take a look at the official reference AJAX of JQuery. My original answer was wrong, coz I suppose you already have the data. A simplified use case for your ajax request would be:
> Initiate the Request, and set the handler for ajax complete (thru something like $.Ajax)
> Hide the content pane and show the loader
> When ajax complete, you display your content, and hide the loader
Following is the original answer.
I think you are talking about something that's already in the client computer's memory, but you want to display all immediately once it's completed loading. Sounds like those "double buffering" in offline media.
What you can do, is:
// Display the loading screen, you can put any animation
$("#loader").fadeIn();
$("#contentPlaceHolder").hide();
// attach the DOM of the contents to placeholder.
$("#contentPlaceHolder").append(CONTENTS);
// .... similar statements follows.
// and finally..
$("#contentPlaceHolder").show();
$("#loader").fadeOut();

Categories

Resources