I have a form where you have to add an image, either by adding a link or uploading an image. When you load the page there is an input text for the url, and there is a button I scripted to change the HTML of the input text to the input file one.
That works well, but the problem comes when submitting the form, the $_FILE array of that dynamic upload input doesn’t exist.
This is the javascript code to swap the input:
function SwapImageMode()
{
if(imageMode == 0)
{
imageMode = 1;
$("#f_imagearea").html("<input type='file' name='addon_imgupld' id='f_upimgimput' name='addon_imgupld' style='margin-bottom:7px;' accept='image/*' onchange='inputFileChange();'/>");
}
else if(imageMode == 1)
{
imageMode = 0;
$("#f_imagearea").html("<input type='text' name='addon_imgurl' class='styled_imput f_imgimput' onFocus=imgUrlImputFocus(); onBlur=imgUrlImputBlur(); />");
}
}
Php code when the form is submitted:
if(isset($_POST["addon_imgurl"]) && !isset($_POST["addon_imgupld"]))
{
$formImgMethod = 1; // link
}
else if(isset($_POST["addon_imgupld"]) && !isset($_POST["addon_imgurl"]))
{
$formImgMethod = 2; // upload
}
if($formImgMethod == 2)
{
echo($_FILES["addon_imgupld"]["name"]);
}
And this is the error of php:
Notice: Undefined index: addon_imgupld in
C:\xampp\htdocs\addexp\agregar\index.php on line 49
The error is pretty straight-forward. You are trying to access an array key that doesn’t exist, so you’ll need to check for different types of form submissions.
Just write a simple conditional in your PHP form handler:
You’ll want to swap $_REQUEST with whatever type of request was made ($_POST, I assume…).
UPDATE::
This conditional is wrong:
Should be:
UPDATE 2::
Did you set your form encoding type to multipart? If not, add this attribute to your form tag: