RJ’s interesting Form data problem

 AJAX file upload tutorial

So I was trying to figure out how I could upload a file without refreshing the page for a form that I am creating and boy was it a pain. I found this post here (http://www.ajaxf1.com/tutorial/ajax-file-upload-tutorial.html) that allowed me to do the file upload part without refreshing the page. I was ecstatic and thankful to Ajaxf1 when I got it to work.

It is worthwhile to mention that although this comes from a website called ajaxf1 the way that he/she does this upload does not use Ajax it loads the action of the upload form in a hidden iframe not using the xmlhttp object.

But unfortunately my joy was short lived. I soon noticed that I didn’t know how to get the URL of the uploaded image into my form data that would eventually go into my database. After some time lamenting and 2 hours of banging my head against the wall I discovered a very simple solution, shockingly simple actually. I have posted it here because I haven’t seen it anywhere else.

in the upload.php file which can be found at the link above you just change the call to the javascript function like so:

<?php

echo(‘<script language="javascript" type="text/javascript">
window.top.window.stopUpload(‘.$result.’,"’.$target_path.’");
</script>’)

?>

$result is success or not and $target_path is the URL of the uploaded image. Then modify the stopUpload function like so:

function stopUpload(success, pic){
      var result = "";
      if (success == 1){
      document.getElementById("result").innerHTML = "<span class=’msg’>The file was uploaded successfully!</span><br/><br/>";
        document.getElementById("hiddenpic").value = pic;
        }
         else
        {
        document.getElementById("result").innerHTML = "<span class=’emsg’>There was an error during file upload!</span><br/><br/>";
                }
        document.getElementById("f1_upload_process").style.visibility = "hidden";
        return true;
        }

What this ends up doing is that if success = 1 it modifies a hidden field in my form called hiddenpic with the URL of the uploaded image, which was passed into the formula in upload.php.

Oh one other interesting thing is that you cannot nest form tags. If you place the file upload form within your original form clicking upload on the form will submit the form that the upload form is nested within.

If you want it to look as though the upload form is part of the original form you will have to do some fancy css placement tricks.

Hopefully one day someone will find this useful. For the entire explanation of the whole “Ajax”( although it is not really Ajax) upload process go to the original site here.

Peace out ya’ll! hopefully this was not that boring of a read haha.

Leave a Reply