Boardy
Boardy

Reputation: 36225

Posting form to a php script using target attribute to an iframe

I am working on a php/HTML web project and I have a form which contains an input type file which should be posted to a PHP script to upload an image onto the server. In the form tag I am using the target attribute to target an iframe so that it can simulate an AJAX style post, i.e. it posts to the iframe so the iframe does the work without requiring the main page to refresh.

Below is the form that I am using.

    <form method="post" action="phpHandler/image-uploader.php" target="image_upload_frame">
<table>
    <tr>
       <td>
          Image Title:
       </td>
       <td>
         <input type="text" id="txtImageTitle" name="txtImageTitle" />
      </td>
   </tr>
   <tr>
     <td>
         Image File:
     </td>
     <td>
         <input type="file" id="txtImageFile" name="txtImageFile" />
     </td>
   </tr>
</table>

Below is the iframe

<iframe id="image_upload_frame" name="image_upload_frame"></iframe>

Below is the PHP script that the form is supposed to post to.

echo "posting";
    $title = $_POST['txtImageTitle'];
    $tempName = $_FILES['txtImageFile']['name'];

    writeToLog("Image Title:" . $title);
    writeToLog("Temp Name: $tempName\n");

    $data = var_export($_POST, true);
    $fileData = var_export($_FILES, true);

    writeToLog($data);
    writeToLog($fileData);

    function writeToLog($message)
    {
        $fh = fopen('log.txt', 'a');
        fwrite($fh, $message);
        fclose($fh);
    }

The PHP script is being exeucted but the $_FILES and $_POST arrays are empty.

I've tried changing the iframe to contain the src attribute pointing to the php script and removed the action from the form but this doesn't seem to even execute the PHP script.

Thanks for any help you can provide.

Upvotes: 1

Views: 3430

Answers (1)

case1352
case1352

Reputation: 1136

add

enctype="multipart/form-data"

to

 <form method="post" action="phpHandler/image-uploader.php" target="image_upload_frame">

Upvotes: 4

Related Questions