JavaScript / HTML / CSS / PHP

19May/10Off

Form submit like AJAX style using an Iframe

I remember the first time I start using AJAX it was really really amazing :) till I found that I can't send images just text, well I'll show how to upload a file without refreshing the whole page.

Here is you html form code:

1
2
3
4
<form enctype="multipart/form-data" method="post" >
    <input name="image" type="file" />
    <input type="submit" value="Submit" />
</form>

And you have add an Iframe element , doesn't matter in which part of the document but I recommend you put it inside of the form like this, add the target attribute to the form element and put the iframe name attribute as a target, you can hide the iframe with the style display:none.

1
2
3
4
5
<form enctype="multipart/form-data" method="post" target="iframe">
   <input name="image" type="file" />
   <input type="submit" value="Submit" />
   <iframe id="iframe" style="display:none"></iframe>
</form>

Ok the problem is that there's no way to fire the onload event of the iframe (I already tried many ways, and asked many people if you know how please let me know) so you have to do a Script that notice you when the Iframe is ready and not just that, maybe you'll need a response from the server.

So here we have to find a way to receive the data and call back a function when the iframe is loaded.

You can follow this way:

1
2
3
4
5
6
7
8
9
10
11
12
<form action="submitIframe.php" enctype="multipart/form-data" method="post" target="iframe">
    <input name="image" type="file" />
    <input type="submit" value="Submit" />
    <iframe name="iframe" style="display:none;"></iframe>
</form>
<script>
  function myCallBackFunction(data)
  {
    //put your code here
    alert(data);
  }
</script>

So you need to response something like this:

1
2
3
4
<script type="text/javascript">
var data = "<?=$myServerResponse ?>";
parent.myCallBackFunction(data);
</script>

In this case I did it with PHP, this is going to be called within the iframe.

Download code here

   

Fatal error: Call to undefined function home_url() in /nfs/c05/h03/mnt/69250/domains/blog.ramonlechuga.com/html/wp-content/plugins/twitter-widget-pro/tlc-transients.php on line 68