Solved

How to validate 2 forms at once

Posted on 2016-11-04
8
26 Views
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" />
</form>

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.
0
Comment
Question by:Black Sulfur
8 Comments
 

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

if(isset($_FILES['image']))
{
 $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); 
   
  if(move_uploaded_file($tmp,$path)) 
  {
  echo "<img src='$path' width='164px' />";

  }
 } 
 else 
 {
  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:

if(move_uploaded_file($tmp,$path)) 
  {
  echo "<img src='$path' width='164px' />";
 $file_upload = true;

Open in new window

0
 
LVL 108

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.
0
 

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.
2forms.jpg
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 200 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
 */
error_reporting(E_ALL);


// IF THE FILE IS UPLOADED
if (!empty($_FILES)) die( var_dump($_FILES) );


// CREATE OUR WEB PAGE IN HTML5 FORMAT
$htm = <<<HTML5
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<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 {
    min-width:64px;
    max-width:128px;
    border: 1px solid gray;
    padding:2px;
}
</style>

<script src="https://code.jquery.com/jquery-latest.min.js"></script>
<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);
        };
        reader.readAsDataURL(input.files[0]);
    };
};

$(document).ready(function(){
    $(".upld").change(function () {
        readURL(this);
    });
});
</script>

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

<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" />
<br>
<input type="submit" value="Upload" />
</form>

</body>
</html>
HTML5;


// RENDER THE WEB PAGE
echo $htm;

Open in new window

0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
LVL 82

Accepted Solution

by:
hielo earned 275 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:
<?php
session_start();
//rest of your code follows
// then intead of
// $file_upload = true;
// use
$_SESSION['file_upload']=true;

Open in new window


whatever.php also need to start with:
<?php
start_session();

//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

0
 

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

0
 
LVL 19

Assisted Solution

by:NerdsOfTech
NerdsOfTech earned 25 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.
1
 

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!
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Consider the following scenario: You are working on a website and make something great - something that lets the server work with information submitted by your users. This could be anything, from a simple guestbook to a e-Money solution. But what…
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…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

705 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now