0

I am working on a form which need to insert some data with an image without reloading the page. In my side everything is working fine when there is no image filed in the form, but if there is an <input type="file"> in my form, then my code is not passing the file/image information. Can you guys please teach me what to add in my code to upload or pass image please?

My Code HTML Form

<form action="action.php" method="POST" enctype="multipart/form-data" id="myform">
   <input type="hidden" value="access" name="label">
   <input type="text" name="one">
   <input type="text" name="two">
   <input type="file" name="image">
   <button type="submit" id="mybtn">Add Data</button>
</form>
<div id="myresult"></div>

My JavaScript

$('#mybtn').click( function(){
    $.post(
    $('#myform').attr('action'),
    $('#myform:input').serializeArray(),
        function(result) { 
           // Some Stuff...
        }
    );
});

My PHP


include 'database.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $label = ["access"];
    if (in_array($_POST['label'], $label)) {
        switch ($_POST['label']) {
            case 'access':
                $one = $_POST['one'];
                $two = $_POST['two'];
                $file_name = $_FILES['image']['name'];
                $file_size = $_FILES['image']['size'];
                $file_temp = $_FILES['image']['tmp_name'];
                $error = [];
                $valid = [];
                $flag1 = $flag2 = $flag3 = false;
                if (!empty($one)) {
                    // Some validation
                    $flag1 = true;
                } else {
                    $flag1 = false;
                }
                if (!empty($two)) {
                    // Some validation
                    $flag2 = true;
                } else {
                    $flag2 = false;
                }
                if (!empty($file_name)) {
                    // Some validation
                    $flag3 = true;
                } else {
                    $flag3 = false;
                }
                if ($flag1 && $flag2 && $flag3) {
                    // move_uploaded_file() + Insert All data
                    if ($result) {
                        $valid[] = "Data added successfully!";
                    } else {
                        $error[] = "Please try again later!";
                    }
                } else {
                    $error[] = "Something went wrong!";
                }

                // ALERT MESSAGE [error] and [valid]
                if (!empty($error)) {
                    foreach ($error as $value) {
                        echo json_encode($value);
                    }
                }
                if (!empty($valid)) {
                    foreach ($valid as $value) {
                        echo json_encode($value);
                    }
                }
                break;
            default:
                # code...
                break;
        }
    }
}

This code works perfectly without reloading page while there are no input type file. I want to know what code I have to add in my JavaScript section to execute the code successfully with an input type file.

Bearded
  • 45
  • 8
  • I don't think `serializeArray()` supports files; you need to create a [FormData](https://developer.mozilla.org/en-US/docs/Web/API/FormData) object, and append both the file input's `files[0]` and the rest of your form data, for instance as JSON. –  Jul 20 '20 at 10:25
  • can you please edit my code? – Bearded Jul 20 '20 at 10:39
  • Sorry, nope. You need to do the research, post an attempt, ideally as [mre], and we'll gladly help you fix it. –  Jul 20 '20 at 10:41
  • okay I am on it.. thanks – Bearded Jul 20 '20 at 10:46
  • No luck man... I cant. Actually I don't know the process of using FormData. Sry. – Bearded Jul 20 '20 at 11:14
  • Start with `const formData = new FormData(document.getElementById('addForm'));`. However I'm wondering why you're using serializeArray() in the first place? I assume your main goal is to POST the form via ajax instead of regular form submission, so why mess with the form data at all? –  Jul 20 '20 at 11:20
  • Hi @ChrisG I edited my question, can you please check again? Thanks – Bearded Jul 20 '20 at 12:48
  • Here's how to send the form including any files: https://jsfiddle.net/ej1x7k53/ You may have to adjust your PHP code accordingly. –  Jul 20 '20 at 13:11
  • uses code from dupe here: [How to send FormData objects with Ajax-requests in jQuery?](https://stackoverflow.com/questions/6974684/how-to-send-formdata-objects-with-ajax-requests-in-jquery) –  Jul 20 '20 at 13:12
  • Thank you so much, I am studying the information's, hope it will solve my problem. I will let you know when done. – Bearded Jul 20 '20 at 13:27
  • Hi @ChrisG I write some new code and my code is working, except the image is not uploading in the folder. could you please check what I missed? – Bearded Jul 21 '20 at 08:33
  • I added an answer – Bearded Jul 21 '20 at 08:34

1 Answers1

0
$('#dataBtnIMG').click( function(){
    var form = $('#dataFormIMG');
    var formData = new FormData($('#dataFormIMG')[0]);
    $.ajax({
        url: form.attr('action'),
        type: form.attr('method'),
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        success:function(result) {
            // Some Stuff
        }
    });
});
Bearded
  • 45
  • 8
  • This doesn't look like an answer, and even if it were, this question is a duplicate. –  Jul 21 '20 at 09:53
  • The above code is working fine. Also I found the reason, why my image is not uploading in the folder! the reason is, I typed the path of directory in my image upload script wrong. But now everything is okay. Thank you very much for your help @ChrisG – Bearded Jul 22 '20 at 03:48