Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Multiple file upload + AJAX on PHP 1

Status
Not open for further replies.

southbeach

Programmer
Jan 22, 2008
879
US
OK, you cannot upload files using AJAX but you can mimic the process by targeting an iframe when submitting the form - and that is what I am doing.

Writing a script where user will setup a catalog of products. Everything I've done for this site is AJAX based and so I would like to keep this form same as others, hence why I am mimicking the AJAX behavior.

I had a form with two input fields each type file. I am using onchange() event to submit the form and load the image. This works fine except that I was getting an error on FF browser and this made me feel uncomfortable. I then decided to split the form in two and have two forms ... now it does not work at all.

The forms submit but when checking for $_FILES['myfile'], it is not set thus rendering the code useless.

Each form is using a unique name and I am checking for each of these names to process the file to be uploaded. Each form submits to a different iframe and I can see messages I output.

Why would $_FILES['myfile'] be blank?

Thank you all in advance for your assistance!


--
SouthBeach
The good thing about not knowing is the opportunity to learn - Yours truly, 2008.
 
Hi

Sorry for asking this, but given the insignificant amount of details you provided, I have no other question in mind.

Have you set the [tt]enctype[/tt] attribute to [tt]multipart/form-data[/tt] for both [tt]form[/tt]s ?

Feherke.
 
Yes I am. Here is the code for both forms
Code:
		<form name="lzmenuimage" action="<?php echo $_SERVER['PHP_SELF']; ?>" target="iframe01" method="post" enctype="multipart/form-data">
			<input type="hidden" name="fileframe" value="true" />
			<input type="hidden" name="action" id="action" value="1" />
			<input type="hidden" name="target" id="target" value="editlzmenu" />
			<table width="100%" border="0" cellpadding="0" cellspacing="0">
				<tr> 
				  <td>Large Image</td>
				  <td><input name="image" type="file" id="image" value="<?php echo $lzmenu->image; ?>" size="45" maxlength="150" class="required" onchange="jsUpload(this,'1')"><input name="imgstatus" id="imgstatus" type="text" disabled size="30" style="border: 1px solid #333;"  /></td>
				</tr>
			</table>
		</form>
		<form name="lzmenuthumbnail" action="<?php echo $_SERVER['PHP_SELF']; ?>" target="iframe02" method="post" enctype="multipart/form-data">
			<input type="hidden" name="fileframe" value="true" />
			<input type="hidden" name="action" id="action" value="2" />
			<input type="hidden" name="target" id="target" value="editlzmenu" />
			<table width="100%" border="0" cellpadding="0" cellspacing="0">
				<tr> 
				  <td>Small Image</td>
				  <td><input name="thumbnail" type="file" id="thumbnail" value="<?php echo $lzmenu->thumbnail; ?>" size="45" maxlength="150" class="required" onchange="jsUpload(this,'2')"><input name="thumbnailstatus" id="thumbnailstatus" type="text" disabled size="30" style="border: 1px solid #333;" /></td>
				</tr>
			</table>
		</form>

The PHP code to upload the submitted form
Code:
	echo 'Will check for _FILES[image] ... <br />';

    if (isset($_FILES['image']))  // file was send from browser
    {
		echo 'File image is set ...<br />';

        if ($_FILES['image']['error'] == UPLOAD_ERR_OK)  // no error
        {

		echo 'No error uploading image ...<br />';

            $filename = $_FILES['image']['name']; // file name 
            move_uploaded_file($_FILES['image']['tmp_name'], $upload_dir.'/'.$filename);
            // main action -- move uploaded file to $upload_dir 
            $result = 'OK';
        } elseif ($_FILES['image']['error'] == UPLOAD_ERR_INI_SIZE) {
            $result_msg = 'Image is too large!<br />';
        } else {
            $result_msg .= 'Unknown error!<br />';
		}
    } else {
		echo '_files[image] is not set ... <br />';
	}
	echo 'Will check for _FILES[thumbnail] ... <br />';
    if (isset($_FILES['thumbnail']))  // file was send from browser
    {
		echo 'File thumbnail is set ...<br />';

        if ($_FILES['thumbnail']['error'] == UPLOAD_ERR_OK)  // no error
        {
            $filename = $_FILES['thumbnail']['name']; // file name 

		echo 'No error uploading thumbnail ...<br />';

            move_uploaded_file($_FILES['thumbnail']['tmp_name'], $upload_dir.'/'.$filename);
            // main action -- move uploaded file to $upload_dir 
            $result = 'OK';
        } elseif ($_FILES['thumbnail']['error'] == UPLOAD_ERR_INI_SIZE) {
            $result_msg .= 'Image is too large!<br />';
        } else {
            $result_msg .= 'Unknown error!<br />';
		}
    } else {
		echo '_files[thumbnail] is not set ... <br />';
	}


--
SouthBeach
The good thing about not knowing is the opportunity to learn - Yours truly, 2008.
 
have you considered using a pre-packaged simple flash uploader? take a look at the wordpress functionality for example. you can upload multiple files simultaneously and you get a progress bar etc.
 
Hi

That works for me. I get the following responses from the script and the files are uploaded :
Code:
[gray]iframe01[/gray]                                    [gray]iframe02[/gray]
[highlight silver]Will check for _FILES[image] ...         [/highlight]   [highlight silver]Will check for _FILES[image] ...         [/highlight]
[highlight silver]File image is set ...                    [/highlight]   [highlight silver]_files[image] is not set ...             [/highlight]
[highlight silver]No error uploading image ...             [/highlight]   [highlight silver]Will check for _FILES[thumbnail] ...     [/highlight]
[highlight silver]Will check for _FILES[thumbnail] ...     [/highlight]   [highlight silver]File thumbnail is set ...                [/highlight]
[highlight silver]_files[thumbnail] is not set ...         [/highlight]   [highlight silver]No error uploading thumbnail ...         [/highlight]
( I only removed the [tt]value[/tt] of the [tt]file[/tt] [tt]input[/tt]s, because I not have the $lzmenu object and that is ignored in the modern browsers anyway. )

The only unknown piece is the [tt]jsUpload()[/tt] function...


Feherke.
 
Back to this after a long day migrating a window application to an SCO UNIX box ...

This file upload is driving me crazy. I had it working with a FF uncaught error ... I decided to modify code and got rid of the error and with it, everything else.

I changed my code to simplify the PHP side of things and when I print the content of $_FILES, I get
Code:
Array ( [image] => Array ( [name] => Array ( [0] => ) [type] => Array ( [0] => ) [tmp_name] => Array ( [0] => ) [error] => Array ( [0] => 4 ) [size] => Array ( [0] => 0 ) ) )
As you can see, I am getting the error "4 - File not uploaded". Notice that name, tmp_name, type and size are all blank.

Here is my new PHP code
Code:
if (isset($_POST['fileframe'])) 
{
    $result = 'ERROR!!!';
    $result_msg = '';

	print_r($_FILES);
	echo '<br /><br />';
	
	echo 'Will check for _FILES[image] ... <br />';
	echo '_FILE[image][name]['.$_POST['action'].'] is set to: '.$_FILES['image']['name'][$_POST['action']].'<br />';

    if (isset($_FILES['image']['name'][$_POST['action']]))  // file was send from browser
    {
		$filex = $_FILES['image']['name'][0];
		echo 'File image is set ... to: '.$filex.'<br />';
		echo 'File image error set ... to: '.$_FILES['image']['error'][0].'<br />';

        if ($_FILES['image']['error'][0] == UPLOAD_ERR_OK)  // no error
        {

		echo 'No error uploading thumbnail ...<br />';

            $filename = $_FILES['image']['name'][$_POST['action']]; // file name 
            move_uploaded_file($_FILES['image']['tmp_name'][$_POST['action']], $upload_dir.'/'.$filename);
            // main action -- move uploaded file to $upload_dir 
            $result = 'OK';
        } elseif ($_FILES['image']['error'][$_POST['action']] == UPLOAD_ERR_INI_SIZE) {
            $result_msg = 'Image is too large!<br />';
        } else {
            $result_msg .= $_FILES['image']['error'][$_POST['action']];
		}
        // you may add more error checking
        // see [URL unfurl="true"]http://www.php.net/manual/en/features.file-upload.errors.php[/URL]
        // for details 
    } else {
		echo '_files[image] is not set ... <br />';
	}

	echo 'result_msg set to : '.$result_msg.'<br />';

    // This is a PHP code outputing Javascript code.
    echo '<html><head><title>-</title></head><body>';
    echo '<script language="JavaScript" type="text/javascript">'."\n";
    echo 'var parDoc = window.parent.document;';
    // this code is outputted to IFRAME (embedded frame)
    // main page is a 'parent'

    $imgID = 'image'; $imgStat = 'imgstatus'; $newimg = 'newimage';
	if($_POST['action'] > 0) 
	{ 
		$imgID = 'thumbnail';
		$imgStat = 'thumbnailstatus';
		$newimg = 'newthumbnail';
	}
	if ($result == 'OK')
    {
        // Simply updating status of fields and submit button
        echo 'parDoc.getElementById("'.$imgStat.'").value = "Successfully Uploaded!";';
        echo 'parDoc.getElementById("saveform").style.display = "block";';
        // echo 'parDoc.getElementById("'.$imgID.'").value = "'.$filename.'";';
        echo 'parDoc.getElementById("'.$newimg.'").value = "'.$filename.'";';
    }
    else
    {
        echo 'parDoc.getElementById("'.$imgStat.'").value = "ERROR: '.$result_msg.'";';
    }

    echo "\n".'</script></body></html>';

    exit(); // do not go futher 

} elseif (isset($_POST['target'])) {
	if($_POST['category'] < 1) { $result_msg .= 'Please select a category!<br />'; }
	if($_POST['name'] == '') { $result_msg .= 'Please enter a name!<br />'; }
	if($_POST['price'] < .01) { $result_msg .= 'Please enter a price!<br />'; }
	if($_POST['description'] == '') { $result_msg .= 'Please enter a description!<br />'; }
}

As far as the JS function jsUpload, here is the code
Code:
function jsUpload(upload_field,img)
{
    // this is just an example of checking file extensions
    // if you do not need extension checking, remove 
    // everything down to line
    // upload_field.form.submit();

    var re_text = /\.jpg|\.gif|\.png/i;
    var filename = upload_field.value;
    var status = 'imgstatus';
	if(img > 0) status = 'thumbnailstatus';

    /* Checking file type */
    if (filename.search(re_text) == -1)
    {
		document.getElementById(status).value = "File must be jpg, gif or png!";
        return false;
    }

    document.getElementById('action').value = img;
	document.getElementById(status).value = "uploading file...";
    upload_field.disabled = true;
	upload_field.form.submit();
    return true;
}

I love the fact that the code works on your end. This means that the logic is functional and that I am missing something very simple.

It might be worth mentioning that the routine responsible for processing the submitted form is included by index.php as it checks for parameters and determines proper course of action. I am going to set my form action to go directly to the PHP script and bypass index.php ... I do not think this is the root cause of my problem but worth a try.

Thanks,



--
SouthBeach
The good thing about not knowing is the opportunity to learn - Yours truly, 2008.
 
jpadie,

There is more to the process than uploading the images. These are just part of the whole picture. These are loaded within a 2nd <form> block in a page where I have at least one other <form> block.

The idea is to mimic AJAX on the part of loading the images as I use AJAX for the other fields and forms throughout the application.

You see, the file type input fields trigger submission of form as they change in value. The loaded files are then placed in a temporary repository where the final form submission will look for and move them to their final store place.

I have never have this file not uploaded problem ... I hate the fact that it was loading fine but for the uncaught error I was getting in FF.

Thanks,


--
SouthBeach
The good thing about not knowing is the opportunity to learn - Yours truly, 2008.
 
doesn't matter. you can still use flash to the uploading as part of any other scripting you want to do (in whatever language you want to do it).
 
I finally got this thing to work ... Took a couple of days off and came back with a fresh mindset.

It turned out that the error I was getting was due to my disabling the element that triggered the jsUpload(). Instead of disabling the element, I opted to hide it by wrapping it within a <div></div> layer and changing the layer properties.

I noticed that if I loaded 2nd image and then the 1st image, I did not get the error so, it became obvious what the root cause of the error was.

While at it, I made it so that if I need to add more elements in the future, I am using file[] as the element name instead of smallimage, bigimage... as per my original post.

Thank you guys for you time and suggestions!



--
SouthBeach
The good thing about not knowing is the opportunity to learn - Yours truly, 2008.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top