Which of the following code is better in building a delete -action for removing a question?
1 My code
<a href='index.php?delete_post=777>delete</a>
2 Stack Overflow's code
<a id="delete_post_777>">delete</a>
I do not understand completely how Stack Overflow's delete -button works, since it points to no URL.
The id apparently can only be used by CSS and JavaScript.
Stack Overflow apparently uses JavaScript for the action.
How can you put start the delete -action based on the content of CSS -file by JavaScript?
How can you start a SQL delete -command by JavaScript? I know how you can do that by PHP, but not by JavaScript.
Your method is not safe as a user agent could inadvertently crawl the link and delete the post without user intervention. Googlebot might do that, for instance, or the user's browser might pre-fetch pages to speed up response time.
From RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1
9.1.1 Safe Methods
Implementors should be aware that the
software represents the user in their
interactions over the Internet, and
should be careful to allow the user to
be aware of any actions they might
take which may have an unexpected
significance to themselves or others.
In particular, the convention has been
established that the GET and HEAD
methods SHOULD NOT have the
significance of taking an action other
than retrieval. These methods ought to
be considered "safe". This allows user
agents to represent other methods,
such as POST, PUT and DELETE, in a
special way, so that the user is made
aware of the fact that a possibly
unsafe action is being requested.
Naturally, it is not possible to
ensure that the server does not
generate side-effects as a result of
performing a GET request; in fact,
some dynamic resources consider that a
feature. The important distinction
here is that the user did not request
the side-effects, so therefore cannot
be held accountable for them.
The right way to do this is to either submit a form via POST using a button, or use JavaScript to do the deletion. The JavaScript could submit a hidden form, causing the entire page to be reloaded, or it could use Ajax to do the deletion without reloading the page. Either way, the important point is to avoid having bare links in your page that might inadvertantly be triggered by an unaware user agent.
Bind a click event on the anchor which start with "delete_post_" and use that to start an Ajax request.
$("a[id^='delete_post_']").click(function(e){
e.preventDefault(); // to prevent the browser from following the link when clicked
var id = parseInt($(this).attr("id").replace("delete_post_", ""));
// this executes delete.php?questionID=5342, when id contains 5342
$.post("delete.php", { questionID: id },
function(data){
alert("Output of the delete.php page: " + data);
});
});
//UPDATE
With the above $.post(), JavaScript code calls a page like delete.php?id=3425 in the background. If delete.php contains any output it will be available to you in the data variable.
This is using jQuery. Read all about it at http://docs.jquery.com/How_jQuery_Works.
The url you are looking for is in the js code. Personally I would have an id that identifies each <a> tag with a specific post, comment... or whatever, and then have a class="delete_something" on each one, this then posts to the correct place using javascript.
Like so:
Delete
<script type="text/javascript">
jQuery('a.delete_post').live('click', function(){
jQuery.post('delete.php', {id: jQuery(this).attr('id')}, function(data){
//do something with the data returned
})
});
</script>
You're quite correct that absent an href="..." attribute, the link would not work without JavaScript.
Generally, what that JavaScript does is use AJAX to contact the server: that's Asynchronous JavaScript and XML. It contacts a server, just as you would by visiting a page directly, but does so in the background, without changing what page the browser is showing.
That server-side page can then do whatever processing you require. In either case, it's PHP doing the work, not JavaScript.
The primary difference when talking about efficiency is that in a traditional model, where you POST a form to a PHP page, after finishing the request you must render an entire page as the "result," complete with the <head>, and with all the visible page content.
However, when you're doing a background request with AJAX, the visitor never sees the result. In fact, it's usually not even a human-readable result. In this model, you only need to transfer the new information that JavaScript can use to change the page.
This is why AJAX is usually seen as being "more efficient" than the traditional model: less data needs to travel back and forth, and the browser (typically) needs to do less work in order to show the data as part of the page. In your "delete" example, the only communication is "delete=777" and then perhaps "success=true" (to simplify only slightly) — a tiny amount of information to communicate for such a big effect!
It all depends on how your application is built, what happens at Stack Overflow is that the delete link click is caught by JavaScript and an Ajax request is being made to delete the post.
You can use a JavaScript library to easily catch clicks on all elements that match your selector rule(s).
Then you can use Ajax to send a request to the PHP script to do the SQL work.
On a side note, ideally you would not use GET for deleting entries, but rather POST, but that's another story.
Related
Let's suppose we have an ASP.Net Web Form, Page.aspx, in which we do the following:
<script>
$(document).ready(function () {
// grab the standard ASP.Net form
var form = document.forms['ctl01'];
form.addEventListener("submit", function (event) {
event.preventDefault();
sendData(form);
});
});
function sendData(form) {
const xhr = new XMLHttpRequest();
const fd = new FormData(form);
xhr.addEventListener("load", function (event) {
document.open();
document.write(event.target.response);
document.close();
});
xhr.addEventListener("error", function (event) {
alert('Error!');
});
xhr.open("POST", "Page.aspx");
xhr.send(fd);
}
</script>
The reason for this setup is I want to take advantage of the XMLHttpRequest progress event to erm, show some progress indication because the postback may include files that take some time to upload.
The load event handler works great. As a result of the POST I get the contents of Page.aspx again and replace my current document. So it seems that some kind of POST actually does happen BUT, there is one problem. In Page.Load(), the Request.Form and Request.Files collections are empty so I can't process the form/files.
I tried adding the following header but without much luck:
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
Do you think it is possible to make a successful POST (with page receiving data) using XMLHttpRequest/FormData, or is there some fundamental limitation that prevents this from happening for ASP.Net pages?
Thanks!
Well any ajax call simply can run some code behind, but since the web page IS STILL sitting on the client side in the browser, then things like controls and the page state are NOT available.
So you don’t want a post back, but now you asking for a post back? (I am confused). I mean, either you post back the whole page (standard event post back). Or you drop the controls and things in question into a update panel, and then ONLY that part of the page is posted back. I fail to see any advantage of trying to send “more” of the page in a ajax call when the WHOLE idea is to NOT send the page in the first place, right?
I mean, if you need some extra values in the ajax call, then you have to get/grab those bits and parts from the page, and include that information in your ajax call. (perhaps as a json string).
Without a post back, then viewstate and all of the controls are STILL just sitting on the users desktop in the browser. The code behind, and even the page class object + code ARE OUT OF scope at this point in time. Only upon a post-back does the WHOLE page travel up to server - code behind runs - you have use of full controls on the page, and THEN the whole page travels back down to the client side (and this quite much means that JavaScript code will have to re-start!!!
However, if you need a few parts and values in a page and don't want a full post-back? Then simply put those parts into a update panel. you can then in JavaScript for example do this:
varMyAspNetButton = docuement.GetElementById("Button1");
varMyAspNetButton.Click();
The above will save you world poverty and not have to wire up a bunch of js and web methods since the js code simply CLICKS on your button (that is inside the update panel). In this case, of course a whole page post back does NOT occur, but the page load and events do in fact fire - these so called "partial" page post backs means that the code behind is LIMITED to the information (controls) inside of that up-date panel.
However, as noted, if you do a post back, then the browser page NOW travels up to the server - and that quite much means any js code client side is toast and now can't run, since a whole NEW fresh copy of the web page is about to travel down to the client side again - and that re-starts your js code.
As noted, you can do a partial page post back with a update panel. And in js you can fire a "click" or in fact MOST events of asp.net controls on that page with js.
But, then again?
You don't want a full page post back, and you likely don't want all of the controls and the whole page to travel up to the server. But then again you wondering why you can't use or access controls on the page with ajax calls? Well as noted, the server side code behind is OUT of scope and OUT of context when you make ajax calls. The web page does NOT exist server side. We don't know if the user turned off their computer, or will never do anything in that client side browser and web page. The server at that point in time has lost ALL KNOWLEGE of that web page. So any ajax call does not have use of the controls on the page, and does not even have use of viewstate either.
This tends to mean that say when using say a ajax system to up-load files? Well, you can't store the status in the web page server side - since the page DOES NOT really exist at that point in time. So you can call some web methods, and about the ONLY way to keep some values in context is to use session(), since that does not need the web page, or the view state to function and work.
The major down side of session() of course is that if some user has two tabs open or even two different browsers open? Well, session() is SHARED between those pages - so while session() is great, it also shared between ALL copies of web pages for that given user - and thus you need to add code to separate out each session "set" of values, or simply hope that the user will not have two pages in operation for such file up-loads.
But to answer your question?
You can do and achieve partial page pushbacks by using a up-date panela And thus you can have timer code or js code client side to continue to run since a full page life-cycle does NOT occur. In other words, you control what part of the web page will and is sent up to the server side by using a update panel.
If you don't use a up-date panel, then any ajax calls you make WILL have to pass the data from the browser side, since it STILL just sitting on the users desktop, and any code behind can't grab, nor reach out, or see or even KNOW that the web page exists client side.
So you either pass extra values from the web page with your ajax calls OR YOU can use a update panel, drop controls inside and then the partial page post back will ONLY send up and have use of what you want inside of that panel. So you have two really great choices.
And in either case (a full page post back) or a partial one?
Grab a reference to the client side asp.net button, and fire off a .click event. You can I suppose wire up all kinds of _doPostBack in js, but with update panels and the click() trick, then you have a choice of how much of the page gets sent up, and it all quite much automatic wired up for you and saves a TRUCKLOAD of work that you would have to manually write and wire up if you don't use a update panel to control this.
So you get that "partial" page post back, and in that case the code and events inside of that up-date panel can update/see/use/modify controls in that up-date panel, but anything outside of that up-date panel will NOT have traveled up to the server.
And if you don't use a update-panel, then any ajax call is just that - a direct call to the server side - but the web page STAYS client side - thus on-load and any of the controls or objects or in fact the WHOLE class form object that represents that web page IS STILL SITTING client side - thus as noted, no on-load, no code behind can touch or even see or know about the values of controls on that page, and as noted there is also no ViewState either.
The WHOLE idea of ajax calls is that you did not want and never did want the page to travel up to the server, and then be re-rendered, and then re-sent back down to the client side. But you need to be 100% crystal clear here:
Without a page post back (or partial one with update panels), then the web page does NOT exist any more server side. Web pages are state-less and once the round trip has occurred (web page up to server - code behind runs, page sent back to client), then as far as the server is concerned (and you the developer) that web page is GONE and DOES NOT exist anymore at all - it is out of scope and from your point of view (and the server point of view) that web page does NOT exist anymore the instant it been sent back down to the client side. As noted, the only exception that is practical here is session() values - since they are not part of any given web page.
So, you have to decide if you want a partial page post back to get at and modify some values with server side code.
Or you pass the values with your ajax calls and the returned values can then update the browser controls. And of course once you do eventually do that say full page post back, then the code behind can certainly see + use any controls that the client js code changed - but can only do so with that full page post back, or as noted, controls limited to a update panel if we are talking about a partial page post back (update panel).
You either have to include additional data in your ajax calls, or consider using a partial page post back to send up part of the web page if you need to modify that part of the page with code behind. Or as noted, return information with your ajax call, and then update the client side. There not really a in-between choice here.
Say I have page1.html, and this is a queue list of people waiting to see me.
I have access to page2.html, which I use to see the list, and call specific people. When I click on a name on page2.html, page1.html is supposed to append a class to that person's name (which uses css3 animations to make it blink).
The example is lame, but you get what I'm trying to do here... I have read a little bit about XMLHttpRequests, and the 'onreadystatechange', but I'm not sure how this works...
Ideas...
I suppose you could do it like this. Have your page2.html update a database when you click on a person's name. You can flag that person in your database when you click on his name on page2.html
Now on the other end make your page1.html continuously query the database in the background in a JavaScript loop. On requesting the information from the database you can accordingly update page1.html
I hope you get it. Do let me know if there are any loop holes.
This link might be of help: PHP long polling, without excessive database access
What you can do is use the XMLHttpRequest to load data from your page1.html and display it on your page2.html accordingly. You would have to use the request on page2 and return the data on page1.
You can think of page2 as your frontend or client where you would have to interpret the information and display it (in your example display the list and change the class of the person), while page1 is your backend that provides the information for your page2.
For further information about XMLHttpRequests or the concept that it's used for I suggest you have a look at the examples here: https://developer.mozilla.org/en/AJAX
As far as I understand you want to update page1 when you click on person's name on page2. I think there are some cases here:
page2 is a dialog window. When you click a name it can be directly manipulated on page1. No XMLHttpRequest needed here.
page2 is a pop-up window. Almost the same. This article may help you about this one.
page2 is a standalone page, in a different tab/window. Here you need an ajax ( XMLHttpRequest ). When you click on name, this action should be write down somewhere ( server-side, sql or something ), and page1 should check for any changes at some time interval.
I did get a fair number of responses, and while the majority of them required constant javascript pinging or somewhat roundabout approaches (such as Reverse AJAX or COMET, Long Polling, etc.), they each solved the problem.
Nonetheless, a little extra digging, and I found a nugget of tech that fits exactly:
HTML5's Server-Sent Events
(http://dev.w3.org/html5/eventsource/)
This allows the client to declare itself as a 'recipient' of communication from the server, effectively reversing the 'Request first, serve later' approach that is dominant in web technology. The server can initiate communication with the client, without an initial request, allowing me to push updates to clients as and when they become available (such as DB changes).
I am curious to know how "modern" web-apps/sites do postbacks, meaning when they are sending back user-input to the site be processed.
Do modern sites still use the old fashion <form>-tags or do they use some sort of javascript/ajax implementation? or is there even a third option?
I tend to use both, where a full page refresh from a normal <form> submit works, but if JavaScript is enabled you hook up to the submit event and override it. This gives you fancy AJAX if possible, and graceful degradation if it's not.
Here's a quick example (jQuery for brevity):
<form type="POST" action="myPage.htm">
<input type="text" name="UserName" />
<button type="submit">Submit me!</button>
</form>
If the user has no JavaScript, no problem the form works. If they do (and most will) I can do this:
$(function() {
$("form").submit(function() {
$.ajax({
url: this.action,
type: this.type,
data: $(this).serialize(),
success: function(data) {
//do something with the result
}
});
});
});
This allows the graceful degradation, which can be very important (depends on your attitude/customer base I suppose). I try and not screw over users without JavaScript, or if a JavaScript error happens on my part, and you can see from above this can be done easily/generically enough to not be painful either.
If you're curious about content, on the server you can check for the X-Requested-With header from most libraries and if it's present, return just the <form> or some success message (since it was an AJAX request), if it's not present then assume a full page load, and send the whole thing.
It will vary depending on what exactly is being done, but most web-apps will do a combination of AJAX for short content (esp where live/interactive updates are helpful without requiring a page refresh) and "old-fashioned" forms for longer content wherein a full page load is not an issue.
Note that nothing about AJAX prevents its use for long content as well as short.
Also note that from the stand-point of the code driving the server app, there is not necessarily much difference at all between a request coming from a standard form or a request coming from an AJAX submission. You could easily structure a single script to properly respond to both types of request (though in some cases you can save bandwidth by sending a shorter "data-only" response to the AJAX version, since the client-side code can be responsible for parsing the data into meaningful content).
Basically, there are three models.
The traditional form model uses form postbacks for every action that requires going to the server, and may use javascript to perform client-side tasks that make the user's life easier without compromising security (e.g. pre-postback validation). The advantage of this is that such a web application, if written correctly, will work without needing any javascript at all, and it is easier to make it work on a wide range of devices (e.g. audio browsers).
The server-centric ajax model uses ajax calls to provide partial page refreshes; the page is built like in the traditional model, but instead of triggering a full page post-back, client-side script uses ajax calls to send clicks and other events, and retrieves information to replace a part of the document (usually in JSON or XHTML form). Because you don't post the entire page every time, the response is usually quicker. This model is useful if you want to use ajax where possible, but still want to be able to fall back to traditional postbacks if javascript isn't available.
Client-centric ajax takes a different path; the core idea is that you write your entire application in javascript, using ajax to exchange data, not markup. When you click a button, the application sends a request to the server, and receives data. The data is then used for further processing on the client. This is more flexible and usually faster than the other methods, but it requires good knowledge of javascript. Applications written in this style generally don't work at all when javascript is disabled on the client.
Most decent web applications try to put progressive enhancement. Meaning that a simple old fashioned button click results in a form post which can be handled by the server. This is for the scenario of people who use an old browser or turned off javascript for some reason.
The enhancement can be done by using hijaxing. Meaning that that same page can perform, with the help of some ajax, the form post to the server but not the entire page. This enables users with javascript enabled to have a better user experience.
old fashion -tags or do they use some sort of javascript/ajax implementation?
In order to have javascript to work on something you still need that somethingl old fashioned tags. Web applications can be structured down to 3 major parts:
Content: HTML
Layout: CSS
Behavior: javascript/ajax
Internet Explorer (with default settings, which I generally assume will be in effect on the desktops of the Great Unwashed) seems to dislike the idea of accepting attachment content in an HTTP response if the corresponding request wasn't made directly from a user action (like a "click" handler, or a native form submit). There are probably more details and nuances, but that's the basic behavior that's frustrating me.
It seems to me that this situation is common: the user interface in front of some downloadable content — say, a prepared PDF report — allows for some options and inputs to be used in the creation of the content. Now, as with all forms that allow the user to stipulate how an application does something, it's possible that the input will be erroneous. Not always, but sometimes.
Thus there's a dilemma. If the client tries to do something fancy, like run an AJAX transaction to let the server vet the form contents, and then resubmit to get the download, IE won't like that. It won't like it because the actual HTTP transaction that carries the attachment back will happen not in the original user-action event handler, but in the AJAX completion callback. Worse, since the IE security bar seems to think that the solution to all one's problems is to simply reload the outer page from its original URL, its invitation to the user to go ahead and download the suspicious content won't even work.
The other option is to just have the form fire away. The server checks the parameters, and if there's anything wrong it responds with the form-container page, peppered appropriately with error messages. If the form contents are OK, it generates the content and ships it back in the HTTP response as an attached file. In this case (I think), IE is happy because the content was apparently directly requested by the user (which is, by the way, a ridiculously flimsy way to tell good content from bad content). This is great, but the problem now is that the client environment (that is, the code on my page) can't tell that the download worked, so the form is still just sitting there. If my form is in some sort of dialog, then I really need to close that up when the operation is complete — really, that's one of the motivations for doing it the AJAX way.
It seems to me that the only thing to do is equip the form dialogs with messaging that says something like, "Close this when your download begins." That really seems lame to me because it's an example of a "please push this button for me" interface: ideally, my own code should be able to push the buutton when it's appropriate. A key thing that I don't know is whether there's any way for client code to detect that form submission has resulted in an attachment download. I've never heard of a way to detect that, but that'd break the impasse for me.
I take it you're submitting the form with a different target window; hence the form staying in place.
There are several options.
Keep the submit button disabled and do ongoing validation in the background, polling the form for changes to fields and then firing off the validation request for a field as it changes. When the form is in a valid state, enable the button; when it isn't, disable the button. This isn't perfect, as there will tend to be a delay, but it may be good enough for whatever you're doing.
Do basic validation that doesn't require round-trips to the server in a handler for the form's submit event, then submit the form and remove it (or possibly just hide it). If the further validation on the server detects a problem, it can return a page that uses JavaScript to tell the original window to re-display the form.
Use a session cookie and a unique form ID (the current time from new Date().getTime() would do); when the form is submitted, disable its submit button but keep it visible until the response comes back. Make the response set a session cookie with that ID indicating success/failure. Have the window containing the form poll for the cookie every second or so and act on the result when it sees it. (I've never done this last one; not immediately seeing why it wouldn't work.)
I expect there are about a dozen other ways to skin this cat, but those are three that came to mind.
(Edit) If you're not submitting to a different target, you might want to go ahead and do that -- to a hidden iframe on the same page. That (possibly combined with the above or other answers) might help you get the user experience you're looking for.
There's a whole number of really good reasons IE does this, and I'm sure it's not something anyone would argue with - so the main objective is to get around it somehow to make things better for your users.
Sometimes its worth re-thinking how things are done. Perhaps disable the button, use javascript to check when all the fields are filled out, and fire off an ajax request once they are. If the ajax was successful, enable the button. This is but one suggestion, I'm sure there will be more...
Edit: more...
Do simple submission (non-AJAX), and if the checks fail, send a page back rather than an attachment. The page sent back could contain all the information originally submitted (plus whatever error message to the user) so the user doesn't need to fill out the entire form again. And I'm also sure there will be more ideas...
Edit: more...
I'm sure you've seen this type of thing before - and yes, it is an extra click (not ideal, but not hard).... an "if your download fails, click here" -> in this case, do it as you want to do it, but add a new link/button to the page when the AJAX returns, so if the download failed, they can submit the already validated form from a "direct user action". And I'm sure I'll think of more (or someone else will).....
I have been fighting a similar issue for a while. In my case, posting to a hidden iframe didn't work if my web app was embedded in an iframe on another site (third party cookie issues) unless our site was added to the Trusted Sites list.
I have found that I could break up the download into POST and GET sequence. The post returns a short lived GUID that can be used in a GET request to initiate the download. The POST can do the form validation as well as return the GUID in a successful response. Once the client has the GUID, you can set the src property of a hidden iframe element to the download URL. The browser sees the 'Content-Disposition': 'attachement' header and gives the user a download ribbon to download the file.
So far it appears to work in all the latest browsers. Unfortunately it requires you to modify you server side API for downloading the file.
So I have two documents dA and dB hosted on two different servers sA and sB respectively.
Document dA has some JS which opens up an iframe src'ing document dB, with a form on it. when the form in document dB is submitted to a form-handler on server sB, I want the iframe on page dA to close.
I hope that was clear enough. Is there a way to do this?
Thanks!
-Mala
UPDATE: I have no control over dA or sA except via inserted javascript
This isn't supposed to be possible due to browser/JavaScript security sandbox policy. That being said, it is possible to step outside of those limitations with a bit of hackery. There are a variety of methods, some involving Flash.
I would recommend against doing this if possible, but if you must, I'd recommend the DNS approach referred to here:
http://www.alexpooley.com/2007/08/07/how-to-cross-domain-javascript/
Key Excerpt:
Say domain D wants to
connect to domain E. In a nutshell,
the trick is to use DNS to point a
sub-domain of D, D_s, to E’s server.
In doing so, D_s takes on the
characteristics of E, while also being
accessible to D.
Assume that I create page A, that lies withing a frame that covers the entire page.
Let A link to yourbank.com, and you click on that link. Now if I could use javascript that modifies the content of the frame (banking site), I would be able to quite easily read the password you are using and store it in a cookie, send it to my server, etc.
That is the reason you cannot modify the content in another frame, whose content is NOT from the same domain. However, if they ARE from the same domain, you should be able to modify it as you see fit (both pages must be on your server).
You should be able to access the iframe with this code:
window["iframe_name"].document.body
If you just want the top-level to close, you can just call something like this:
window.top.location = "http://www.example.com/dC.html";
This will close out dA and sent the user to dC.html instead. dC.html can have the JS you want to run (for example, to close the window) in the onload handler.
Other people explained security implications. But the question is legitimate, there are use cases for that, and it is possible in some scenarios to do what you want.
W3C defines a property on document called domain, which is used to check security permissions. This property can be manipulated cooperatively by both documents, so they can access each other in some cases.
The governing document is DOM Level 1 Spec. Look at the description of document. As you can see this property is defined there and … it is read-only. In reality all browsers allow to modify it:
Mozilla's document.domain description.
Microsoft's domain property description.
Modifications cannot be arbitrary. Usually only super-domains are allowed. It means that you can make two documents served by different server to access each other, as long as they have a common super-domain.
So if you want two pages to communicate, you need to add a small one-liner, which should be run on page load. Something like that should do the trick:
document.domain = "yourdomain.com";
Now you can serve them from different subdomains without losing their accessibility.
Obviously you should watch for timing issues. They can be avoided if you establish a notification protocol of some sort. For example, one page (the master) sets its domain, and loads another page (the server). When the server is operational, it changes its domain and accesses the master triggering some function.
A mechanism to do so would be capable of a cross-site scripting attack (since you could do more than just remove a benign bit of page content).
A safe approach would limit to just the iframe document emptying/hiding itself, but if the iframe containing it is fixed size, you will just end up with a blank spot on the page.
If you don't have control over dA or Sa this isn't possible because of browser security restrictions. Even the Flash methods require access to both servers.
This is a bit convoluted but may be more legitimate than a straight XSS solution:
You have no control over server A other than writing javascript to document A. But you are opening an iframe within document A, which suggests that you only have write-access to document A. This a bit confusing. Are you writing the js to document A or injecting it somehow?
Either way, here is what I dreamed up. It won't work if you have no access to the server which hosts the page which has the iframe.
The user hits submit on the form within the iframe. The form, once completed, most likely changes something on the server hosting that form. So you have an AJAX function on Document A which asks a server-side script to check if the form has been submitted yet. If it has, the script returns a "submitted" value to the AJAX function, which triggers another js function to close the iframe.
The above requires a few things:
The iframe needs to be on a page hosted on a server where you can write an additional server-side script (this avoids the cross-domain issue, since the AJAX is pointing to the same directory, in theory).
The server within the iframe must have some url that can be requested which will return some kind of confirmation that the form has been submitted.
The "check-for-submitted" script needs to know both the above-mentioned URL and what to look for upon loading said URL.
If you have all of the above, the ajax function calls the server-script, the server-script uses cURL to go the URL that reflects if the form is done, the server-script looks for the "form has been submitted" indicators, and, depending on what it finds, returns an answer of "not submitted" or "submitted" to the ajax function.
For example, maybe the form is for user registration. If your outer document knows what username will be entered into the form, the server-side script can go to http://example.org/username and if it comes up with "user not found" you know the form has yet to be submitted.
Anything that goes beyond what is possible in the above example is probably outside of what is safe and secure anyway. While it would be very convenient to have the iframe close automatically when the user has submitted it, consider the possibility that I have sent you an email saying your bank account needs looking at. The email has a link to a page I have made which has an iframe of your bank's site set to fill the entire viewable part of my page. You log in as normal, because you are very trusting. If I had access to the fact that you hit submit on the page, that would imply I also had access to what you submitted or at the very least the URL that the iframe redirected to (which could have a session ID in or all sorts of other data the bank shouldn't include in a URL).
I don't mean to sound preachy at all. You should just consider that in order to know about one event, you often are given access to other data that you ought not have.
I think a slightly less elegant solution to your problem would be to have a link above the iframe that says "Finished" or "Close" that kills the iframe when the user is done with the form. This would not only close the iframe when the user has submitted the form, but also give them a chance to to say "oops! I don't want to fill out this form anyway. Nevermind!" Right now with your desired automatic solution, there is no way to get rid of the iframe unless the user hits submit.
Thank you everybody for your answers. I found a solution that works:
On my server, I tell the form to redirect to the url that created the iframe.
On the site containing the iframe, I add a setInterval function to poll for the current location of the iframe.
Due to JS sandboxing, this poll does not work while the url is foreign (i.e. before my form is submitted). However, once the url is local (i.e. identical to that of the calling page), the url is readable, and the function closes the iframe. This works as soon as the iframe is redirected, I don't even need to wait for the additional pageload.
Thank you very much Greg for helping me :)