1

I have a html form used to upload file to the server. For brevity, I have only shown the essential peices

 <form id='uploadform' method='post' enctype='multipart/form-data' action='index.php/upload'>
   <input name='myFile' id='myFile' type='file'/>
 </form>
 <input type='button' id='upload' value='Upload'/>
 <div id='response'></div>

I use jQuery.submit() to submit the form:

 $('#uploadform').submit();

Business logic is Slim PHP : $app->post('/upload', 'uploadFile'); ....

   function uploadFile(){
       try{
           // if success uploading
           $app->redirect('/main-page');

       }catch(Exception $e){
           // if error 
           echo $e->getMessage();

       }
    }

Issue: If the upload fails for some reason, an exception is thrown, user is taken to a PHP error page. If upload was completed without exception, the application is redirected to main page.

What is required is: if the upload succeeds the application should be redirected to main-page as it does now...but if there was any exception thrown, instead of going to PHP error page, the application should stay on upload page and with id = 'response' should display exception.

Is it possible to do anything like this with jQuery submit():

     $('#uploadform').submit(function(response){
           $('response').html(response);
     });

????

I know JQuery upload file plugins would make life easier...but that is not an option for me...

Thanks for any pointers!

Is it possible

Vikram
  • 4,162
  • 8
  • 43
  • 65
  • Why can't you use other peoples plugins and instead have to write your own? Also, have you read this? http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously-with-jquery – Nal Sep 01 '12 at 23:23
  • Do you know when exactly the exception occurs ? If you know that you could use `throw()` so that you force your `catch` block to execute the code. I never worked with `slim` so see if this tip helps you. Ignore if i am wrong!! – Deepak Sep 04 '12 at 05:24
  • Is it realy an exception, isn't it php error? If so, the catch block will not be triggered and you will not receive the exception message. – Jakub Truneček Sep 04 '12 at 11:29
  • @Nal there are lots of motives for one to reinvet the wheel: educational purposes, being restricted by licenses or supervisors, the platform used isn't compatible with the plugin or requires massive changes – Vlad Balmos Sep 04 '12 at 11:37
  • Sorry for a late response guys.. thanks Vlad for answering...I cannot use plugin because the environment is really restricted...that is forcing me to rewrite a lot of things that an API like jQuery UI would already have – Vikram Sep 04 '12 at 19:16
  • @JakubTruneček I do get(and throw) Slim Framework exceptions. – Vikram Sep 04 '12 at 19:19
  • My style: rewrite PHP, use $output['success'] = "xxxx" or $output['error'] = "yyyy" and return json_encode($output). On the browser, $.parseJSON(response) and test for response.error/success, then perform redirection. – Alvin K. Sep 05 '12 at 07:24

4 Answers4

2

I had a similar issue in the past, what I've come up with is to use an invisble iframe to post the file upload and get the html result back, hope this helps!

Luc Laverdure
  • 1,398
  • 2
  • 19
  • 36
  • can you please elaborate more on how you were able to bubble up exception such that if upload failed, the app would remain on same page and show error. For me Slim redirects to own error page in case of any exception. I do not want to show any Slim Exceptions to the user – Vikram Aug 30 '12 at 17:55
2

I think this is what you are looking for

html code:

<form id='uploadform' method='post' enctype='multipart/form-data' action='index.php/upload' target="hiddeniframe">
    <input name='myFile' id='myFile' type='file'/>
</form>
<iframe name="hiddeniframe" id="hiddeniframe" style="display: none"></iframe>
<input type='button' id='upload' value='Upload'/>
<div id='response'></div>

i added an hidden iframe and made the target of the form the id of the iframe. This will make the form submit into the iframe so the whole page won't reload

javascript code:

<script type="text/javascript">
    window.showUploadError = function(error) {
        $('#response').html(error);
    };


     $('#uploadform').submit();
</script>

i added a global function named showUploadError which will be called from the php upload function in case of the error

php code

<?php
    function uploadFile(){
        try{
            // if success uploading
            ?>
            <script type="text/javascript">
                parent.location.href = '/main-page'
            </script>
            <?php 
            die();
        }catch(Exception $e){
        // if error 
        ?>
            <script type="text/javascript">
                parent.showUploadError('Upload failed');
            </script>
        <?php
   }
}

if the upload is successfull we output some javascript code which will redirect the parent page (main page) to the new location, otherwise it will call the showUploadError javascript function.

Keep in mind this is a crude example and i haven't tested it.

Vlad Balmos
  • 3,372
  • 19
  • 34
2

You need to use ajax here is example for file upload using ajax

Sending multipart/formdata with jQuery.ajax

with out ajax you can redirect back user and send error text by GET method and put this text in response tag

Community
  • 1
  • 1
Phoebus
  • 661
  • 6
  • 16
  • thanks!..the link you posted is helpful. I am still evaluating your solution. Your solution may work because ajax upload is what I think may solve my problem: I can get around Slim Framework redirect (I know its kind of sloppy) to main page when there is an exception ....will keep you posted...meanwhile I am building this app for IE8 specifically...so I hope FormData class is supported in IE8 – Vikram Sep 06 '12 at 16:16
  • I tried with Chrome, Firefox and IE8. It works on Chrome and Firefox...but does not on IE8(not a surprise though )...Thanks for your answer! I will give this to you – Vikram Sep 06 '12 at 16:35
0

The option you have is to send the "submit" to a "iframe", then with "js" get the response. In PHP you send a message which is then interpreted in "JS".

HTML:

<form id="uploadform" method="post" enctype="multipart/form-data" action="index.php/upload" target="uploadformResponse">
   <input name='myFile' id='myFile' type='file'/>
</form>
<input type='button' id='upload' value='Upload'/>
<div id='response'></div>
<div style="display:none;">
    <iframe name="uploadformResponse" id="uploadformResponse"></iframe>
</div>

Javascript:

var runSubmitForm = function() {

   var 
      $iframe = $('#uploadformResponse'),
      fnLoadIframe = function(event) {
         $iframe.unbind('load');
         var 
             response = $iframe.contents(),
             aresponse = response.split('|');  

         console.log('debug respnse', response);

         if (aresponse.length != 2) {
            $('#response').html("Error I ???");
         }

         if (aresponse[0] == '1') {
             window.location = aresponse[1];
         }
         else if (aresponse[0] == '0') {
            $('#response').html(aresponse[1]);
         }
         else {
            $('#response').html("Error II ???");
         }
      };

   $iframe.bind('load', fnLoadIframe);
   $('#uploadform').submit();
};

PHP:

function uploadFile(){
   try{
      // if success uploading
      echo '1|/main-page';
   } catch(Exception $e) {
      // if error 
      echo '0|' . $e->getMessage();
   }
   exit; // optional
}
andres descalzo
  • 14,887
  • 13
  • 64
  • 115