Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win


How to validate 2 forms at once

Posted on 2016-11-04
Medium Priority
Last Modified: 2016-11-05
I need a bit of help with the logic of this, please.

I have 2 forms. The one form has text fields and drop downs that have be filled in e.g.: product name, price, category etc.

Then next to it I have another form with the ability to upload a single image which is meant to be a featured image.

When I click submit I want to be able to check that an image has been selected and  uploaded. But the problem is that the image has it's own form with it's own upload button that needs to be pressed.

So, if I click on submit to add a product, it is only checking that the submit button was pressed and not that the upload button had already been pressed. Not sure if I am making any sense as it's hard to explain. I will post some code which might help.

here is an example of some of the validation for the main form with all the details of the product with a button name of "add_product"

if(isset($_POST['add_product'])) {
		if(empty($_POST['prod_name'])) {
			$message .= "Product name required <br />";
		if(empty($_POST['category'])) {
			$message .= "Category required <br />";

Open in new window

The upload form:

<form id="form" action="ajaxupload.php" method="post" enctype="multipart/form-data">
<input id="uploadImage" type="file" accept="image/*" name="image" class="form-control" />
<input type="submit" id="button" name="upload" class="btn btn-fill btn-danger" value="Upload" />

Open in new window

I thought about putting the image upload into the same form so they were both in 1 form but it isn't possible because the form with the image upload posts to ajaxupload.php and the other form is going to submit to the database.
Question by:Black Sulfur
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions

Author Comment

by:Black Sulfur
ID: 41874248
This is the php on the ajaxupload.php

$valid_extensions = array('jpeg', 'jpg', 'png', 'gif', 'bmp'); // valid extensions
$path = 'uploads/'; // upload directory

 $img = $_FILES['image']['name'];
 $tmp = $_FILES['image']['tmp_name'];
 // get uploaded file's extension
 $ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));
 // can upload same image using rand function
 $final_image = rand(1000,1000000).$img;
 // check's valid format
 if(in_array($ext, $valid_extensions)) 
  $path = $path.strtolower($final_image); 
  echo "<img src='$path' width='164px' />";

  echo 'invalid file';

Open in new window

I thought that maybe I could set a variable once they upload has completed and then check if it exists when I try submit the other form but not sure. So, after I echo the image, I set something like:

  echo "<img src='$path' width='164px' />";
 $file_upload = true;

Open in new window

LVL 111

Expert Comment

by:Ray Paseur
ID: 41874669
Why not just use one form?  It's a POST-method request, so you can send other fields along with the file upload.

To expand on the idea a little more, each form submission is made via an HTTP request.  If you can make one request instead of two, your application design will be greatly simplified!

Looking forward to the redesign that you're going to have to do after this initial implementation is set up, you might want to consider these ideas...

1. All images associated with a product must be replaceable.
2. All data fields associated with a product must be replaceable.
3. The order of presentation for the images must be user-settable.
4. Any image must be able to be deleted or overwritten.

When you take those ideas into account you will come to a set of simpler table maintenance scripts, and the programming (as well as the application) will be simplified.

Author Comment

by:Black Sulfur
ID: 41874682
I want to be able to see the preview of the image uploaded which means the image needs to upload first. Doesn't that mean it has to be in a seperate form to upload separately to submitting the form with all the text fields? perhaps I am just making this too complicated because I want it to work like the wordpress version.

I have uploaded an image so you can see what I mean. I want to upload the image and show it on the right. Then if the user hasn't uploaded the image, when they click the button on the left form they should get an error to say that they need to upload an image. I just like the idea of them being able to see a thumbnail of the image they uploaded instead of just seeing the filename.
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

LVL 111

Assisted Solution

by:Ray Paseur
Ray Paseur earned 800 total points
ID: 41874794
You might find that you can preview image uploads with some HTML5 controls.  See if this looks good...
<?php // demo/upload_image_preview.php
 * http://www.experts-exchange.com/questions/28935721/Show-the-uploaded-image-file-on-the-page.html
 * https://developer.mozilla.org/en-US/docs/Web/API/FileReader
 * https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API

if (!empty($_FILES)) die( var_dump($_FILES) );

$htm = <<<HTML5
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<meta charset="utf-8" />
<meta name="robots" content="noindex, nofollow" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />

<style type="text/css">
.preview img {
    border: 1px solid gray;

<script src="https://code.jquery.com/jquery-latest.min.js"></script>
function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $(".preview img").attr("src", e.target.result);

    $(".upld").change(function () {

<title>File Upload With Image Preview</title>

<noscript>Your browsing experience will be much better with JavaScript enabled!</noscript>

<div class="preview"><img src="" /></div>
<form enctype="multipart/form-data" method="post">
<input type="file" class="upld" name="myfile" />
<input type="submit" value="Upload" />


echo $htm;

Open in new window

LVL 82

Accepted Solution

hielo earned 1100 total points
ID: 41875159
>> When I click submit I want to be able to check that an image has been selected and  uploaded.
OK, from what you already have, since you two different files -- ajaxupload.php and whatever.php (for the product name, etc) -- since these files execute at different times, you cannot use $file_upload = true; because it will exist only in ajaxupload.php while it is processing the upload.  What you need to do is to use $_SESSION variables.  Put the following at the start of your ajaxupload.php:
//rest of your code follows
// then intead of
// $file_upload = true;
// use

Open in new window

whatever.php also need to start with:

//rest of your code here
//and then to see if the file was uploaded use:
if( array_key_exists('file_uploaded',$_SESSION) && true===$_SESSION['file_uploaded'])
  // file was uploaded

Open in new window


Author Comment

by:Black Sulfur
ID: 41875191
Okay, both of these are great so far. Thanks guys!  

Great idea with the session variable, that worked perfectly. Only one issue with it..

If I don't upload an image and I try submit, I now get the error message I set that says I need to upload an image. If I upload the image and submit, I don't get the error which is exactly what I want to happen. BUT, if there is something else wrong with the form and it is submitted (like a field left empty for example), it shows the errors and the image that was uploaded disappears now. I assume that's because when I submit the form it is posting and refreshing the page.

I tried to put the uploaded image into a session variable as well so that it would still display even after page refresh but that didn't work.

 $_SESSION['imguploaded'] = true;
	$_SESSION['showimage'] = "<img src='$path' width='164px' />";
	   echo $_SESSION['showimage'];

Open in new window

LVL 19

Assisted Solution

NerdsOfTech earned 100 total points
ID: 41875208
I recommend that there be 1 form (multi-part type) and that the upload button initiate a "local" preview of the image (load file from users hard drive via file: protocol when the upload button is clicked {onclick}) . The submit button will act as the true upload button. Attach a Javascript OnSubmit procedure to the submit button to check to see if the file is present or  stop the submission of the form (Javascript: return false;) until the image is present.

Author Comment

by:Black Sulfur
ID: 41875398
Trying to use 2 forms is way too complicated for me at this stage I would say. I think I will take the advice of using 1 form. However, I must say that the session variable method was working for me but trying to show the image straight away was an issue and a bunch of other stuff. I have got some good advice here to get me going though. Thanks to all!

Featured Post

Tech or Treat!

Submit an article about your scariest tech experience—and the solution—and you’ll be automatically entered to win one of 4 fantastic tech gadgets.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
This article discusses four methods for overlaying images in a container on a web page
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to count occurrences of each item in an array.
Suggested Courses

610 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question