0

I have a button once clicked it will display the user with a set of fields along with a browse button to upload an image. Example:

Button: Add Student

once clicked, the fields showing: First name, Last name, email, major and then a browse button to upload an image.

Since this is all part of a form and the user can add multiple students before saving the form - I am running into an issue when the user fills out the fields and select the image to upload it uploads but the page refreshes which causes the unsaved data to be lost. Is there a way i can upload the image and retrieve the image id but once i save the form i will be saving the image id as part of the student information in the database.

This is what i have:

<div class="col-lg-4">
<div class="form-group mb-2">Student #1</div>
<div class="form-group mb-2">First Name <input class="form-control" name="first_name[]" type="text" /></div>
<div class="form-group mb-2">Last Name <input class="form-control" name="last_name[]" type="text" /></div>
</div>
<div class="col-lg-4">
<div class="form-group mb-2">Email <input class="form-control" name="email[]" type="text" /></div>
<div class="form-group">Major <input class="form-control" name="major[]" type="text" /></div>
</div>
<div class="row">
<div class="col-lg-4">
<div class="form-group mb-4"><label for="student_photo">Student Photo</label><br /><input accept="image/*" name="student_photo" type="file" /> <input name="submit_student_image" type="submit" value="Upload" /></div>
<div class="form-group mb-4">&nbsp;</div>
</div>
</div>
<div class="col-lg-4">
<div class="form-group mb-2">Student #2</div>
<div class="form-group mb-2">First Name <input class="form-control" name="first_name[]" type="text" /></div>
<div class="form-group mb-2">Last Name <input class="form-control" name="last_name[]" type="text" /></div>
</div>
<div class="col-lg-4">
<div class="form-group mb-2">Email <input class="form-control" name="email[]" type="text" /></div>
<div class="form-group">Major <input class="form-control" name="major[]" type="text" /></div>
</div>
<div class="row">
<div class="col-lg-4">
<div class="form-group mb-4"><label for="student_photo">Student Photo</label><br /><input accept="image/*" name="student_photo" type="file" /> <input name="submit_student_image" type="submit" value="Upload" /></div>
<div class="form-group mb-4">&nbsp;
</div>
</div>
<div class="col-lg-4">
<div class="form-group mb-2">Student #3</div>
<div class="form-group mb-2">First Name <input class="form-control" name="first_name[]" type="text" /></div>
<div class="form-group mb-2">Last Name <input class="form-control" name="last_name[]" type="text" /></div>
</div>
<div class="col-lg-4">
<div class="form-group mb-2">Email <input class="form-control" name="email[]" type="text" /></div>
<div class="form-group">Major <input class="form-control" name="major[]" type="text" /></div>
</div>
<div class="row">
<div class="col-lg-4">
<div class="form-group mb-4"><label for="student_photo">Student Photo</label><br /><input accept="image/*" name="student_photo" type="file" /> <input name="submit_student_image" type="submit" value="Upload" /></div>
<div class="form-group mb-4">&nbsp;</div>
</div>
</div>

This is my upload function:

 if(isset($_POST['submit_student_image'])){
    // Get Image Dimensions
    $studentImageInfo = @getimagesize($_FILES["student_photo"]["tmp_name"]);
    $width = $studentImageInfo[0];
    $height = $studentImageInfo[1];

    $allowed_image_extension = array(
        "png",
        "jpg",
        "gif"
    );
    // Get file extension
    $file_extension = pathinfo($_FILES["student_photo"]["name"], PATHINFO_EXTENSION);
    // Validate file input to check if is not empty
    if (! file_exists($_FILES["student_photo"]["tmp_name"])) {
        $response = array(
            "type" => "error",
            "message" => "Choose image file to upload."
        );
    }    // Validate file input to check if is with valid extension
    elseif (! in_array($file_extension, $allowed_image_extension)) {
        $response = array(
            "type" => "error",
            "message" => "Upload valid images. Only PNG and JPEG are allowed."
        );
    }    // Validate image file size
    elseif (($_FILES["student_photo"]["size"] > 1000000)) {
        $response = array(
            "type" => "error",
            "message" => "Image size exceeds 1MB"
        );
    }    // Validate image file dimension
    elseif ($width > "600" || $height > "450") {
        $response = array(
            "type" => "error",
            "message" => "Image dimension should be within 300X200"
        );
    }
     else {
        $file = array(
            'name' => $_FILES["student_photo"]["name"],
            'type' => $_FILES["student_photo"]["type"],
            'tmp_name' => $_FILES["student_photo"]["tmp_name"],
            'size' => $_FILES["student_photo"]["size"]
        );
        $upload = wp_handle_upload($file, array('test_form' => false));
        if(!empty($upload['error'])){
            echo "some error";
            return false;
        }
        $check_page_exist = get_page_by_title($lender->slug, OBJECT, 'page');
        $attachment_id = wp_insert_attachment(array(
            'guid' => $upload['url'],
            'post_mime_type' => $upload['type'],
            'post_title' => basename($upload['file']),
            'post_content' => '',
            'post_status' => 'inherit'
        ), $upload['file'], $check_page_exist->ID);
        if(is_wp_error($attachment_id) || !$attachment_id){
            wp_die('Upload error.');
        }
        wp_update_attachment_metadata($attachment_id, wp_generate_attachment_metadata($attachment_id, $upload['file']));

        $student_photo_id = wp_get_attachment_url($attachment_id);
    }

When the user saves the whole page this is how i am saving the fields:

if(!empty($first_name) && !empty($last_name) && !empty($email) && !empty($major)){
            foreach($email as $key=>$value){
                if(!empty($value)){
                    $wpdb->insert("wp_directory", array(
                        'major'         => $major[$key],
                        'first_name'     => $first_name[$key],
                        'last_name'       => $last_name[$key],
                        'email'         => $email[$key],
                        'photo_id'     => // student_photo_id,
                        'status'            => 'Active'
                    ));
                }
            }
            
        }

In short - I am little confused how i can save an upload to a group of fields without having to refresh the page and loosing data? Will all the photos be saved and ids pushed into an array and when i save the student fields i will also use the $key to assign the proper student photo id with the student info?

bluePearl
  • 1,237
  • 4
  • 24
  • 42
  • **Hint:** (1) upload the image, and send to server thru ajax and (2) then on return update the DIV containing the image – Ken Lee Nov 14 '22 at 02:42
  • @KenLee i am a bit new to php and was wondering if you can maybe direct me to an example using ajax i can review. – bluePearl Nov 14 '22 at 02:43
  • Does this answer your question? [Ajax Upload image](https://stackoverflow.com/questions/19447435/ajax-upload-image) Note: after upload, instead of executing something like `console.log("success");` , update the img div – Ken Lee Nov 14 '22 at 02:52
  • @KenLee looking over that example it seems like i would need a form tag within a form tag which doesn't work - I will try something and see how far i can get. – bluePearl Nov 14 '22 at 03:51

0 Answers0