0

After submitting the form I can't get post data, no clue where is the problem but I think it's the js file. I'm not advanced in using Ajax so I guess this is the problem.

I'm getting error that can't get $name, $projectFile etc.

So should I rewrite the js or PHP? There are no syntax errors, I want this form to be dynamically submitted with Ajax.

html

<form enctype="multipart/form-data" id="upload-form" class="upload-container">
     <label for="projectname">Project Name</label>
     <input type="text" id="projectname" name="projectname">
     <label for="projecturl">Project Link (Gitlab/Github)</label>
     <input type="text" id="projecturl" name="projecturl">
     <div class="fileuploader">
         <label for="projectpreview">Project Upload</label>
         <input type="file" id="projectpreview" name="projectpreview">
     </div>
     <label for="projectwebsite">Project Website</label>
     <input type="text" id="projectwebsite" name="projectwebsite">
     <button type="submit" id="upload">Add Project</button>
</form>

js

$('#upload-form').on('submit', (e) => {
        e.preventDefault();
        let $this = $(this);
        let $name = $('#projectname');
        let $url = $('#projecturl');
        let $file = $('#projectpreview');
        let $web = $('#projectwebsite');
        $.ajax({
            url: '../assets/upload.php',
            type: 'POST',
            data: new FormData($(this)),
            contentType: false,
            cache: false,
            processData: false,
            success: (response) => {
                console.log(response);

            }
        });
        // VALIDATION
        $('#file').change(() => {
            let file = this.files[0];
            let imageFile = file.type;
            let match = ['image/jpeg', 'image/png', 'image/jpg'];
            if (!((imageFile == match[0]) || (imageFile == match[1]) || (imageFile == match[2]))) {
                alert('Pleas select valid file: JPEG, PNG, JPG');
                $('#file').val('');
                return false;
            }
        });
    });

php

<?php

include('db.php');

$name = $_POST['projectname'];
$projectUrl = $_POST['projecturl'];
$projectFile = $_FILES['projectpreview'];
$projectWebsite = $_POST['projectwebsite'];
$date = date('Y-m-d H:i:s');

if (!empty($name) || !empty($projectUrl) || !empty($projectFile['name']) || !empty($projectWebsite)) {
    $upFile = '';
    if (!empty($projectFile['type'])) {
        $fileName = time().'_'.$projectFile['name'];
        $valid_extensions = array('jpeg', 'jpg', 'png');
        $temporary = explode('.', $projectFile['name']);
        $file_extension = end($temporary);
        if ((($_FILES['hard_file']['type'] == 'image/png') || ($projectFile['type'] == 'image/jpeg') || ($projectFile['type'] == 'image/jpg')) && in_array($file_extension, $valid_extensions)) {
            $sourcePath = $projectFile['tmp_name'];
            $targetPath = 'img/photos/'.$fileName;
            if (move_uploaded_file($sourcePath, $targetPath)) {
                $uploadedFile = $fileName;
            }
        }
    }
    if ($connection->query("INSERT INTO projects VALUES('', '$name', '$projectUrl', '$uploadedFile', '$projectWebsite', '$date')")) {
        exit('success');
    } else {
        exit('fail');
    }
}

AS Mackay
  • 2,831
  • 9
  • 19
  • 25
  • 2
    check in your browser console for XHR requests, You should find this request with all your request data – Dhanu K Mar 28 '19 at 08:30
  • Remove `contentType` from the ajax arguments, it prevents proper header to be sent. – Teemu Mar 28 '19 at 08:31
  • Could you post the actual error? Like in which line,file... – Mikel Ferreiro Mar 28 '19 at 08:33
  • 3
    Why use `FormData` when you don't seem to be doing any file uploads? Just do: `data: $(this).serialize()` and it should do what you want. You should also remove `contentType` and `processData` from the ajax request. – M. Eriksson Mar 28 '19 at 08:34
  • @MagnusEriksson there is upload for image fiels –  Mar 28 '19 at 08:38
  • Not in the request since you're not adding the files to the FormData object. See this post on how to add the files and extra parameters properly: https://stackoverflow.com/a/21045034/2453432 – M. Eriksson Mar 28 '19 at 08:39
  • The FormData constructor wants the HTML form element as parameter, you are providing a jQuery object instead. `data: new FormData(this),` – 04FS Mar 28 '19 at 08:49
  • Can you check for the request in the browser console and attach the data that was sent on an example request to your question? – Nico Haase Mar 28 '19 at 09:24

2 Answers2

0

i think you have to remove the contentType argument (and use serializeArrayfrom your Form jQuery Object):

    $.ajax({
        url: '../assets/upload.php',
        type: 'POST',
        data: $(this).serializeArray(),
        processData: false,
        success: (response) => {
            console.log(response);

        }
    });
silly
  • 7,789
  • 2
  • 24
  • 37
0

Convert form fields to key value page and then pass that as the data in AJAX.

$('#upload-form').on('submit', (e) => {
    e.preventDefault();
    let $this = $(this);
    var formData = "";
    $.each($('#upload-form').serializeArray(), function(i, field) {
        formData += field.name + ": \""+ field.value + "\","
    });
    formData = formData.replace(/^,|,$/g,'');
    console.log(formData);
    $.ajax({
        url: '../assets/upload.php',
        type: 'POST',
        data: formData,
        contentType: false,
        cache: false,
        processData: false,
        success: (response) => {
            console.log(response);

        }
    });
    // VALIDATION
    $('#file').change(() => {
        let file = this.files[0];
        let imageFile = file.type;
        let match = ['image/jpeg', 'image/png', 'image/jpg'];
        if (!((imageFile == match[0]) || (imageFile == match[1]) || (imageFile == match[2]))) {
            alert('Pleas select valid file: JPEG, PNG, JPG');
            $('#file').val('');
            return false;
        }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form enctype="multipart/form-data" id="upload-form" class="upload-container">
     <label for="projectname">Project Name</label>
     <input type="text" id="projectname" name="projectname">
     <label for="projecturl">Project Link (Gitlab/Github)</label>
     <input type="text" id="projecturl" name="projecturl">
     <div class="fileuploader">
         <label for="projectpreview">Project Upload</label>
         <input type="file" id="projectpreview" name="projectpreview">
     </div>
     <label for="projectwebsite">Project Website</label>
     <input type="text" id="projectwebsite" name="projectwebsite">
     <button type="submit" id="upload">Add Project</button>
</form>
Sami Ahmed Siddiqui
  • 2,328
  • 1
  • 16
  • 29