简体   繁体   English

PHP 7.x无法使用Ajax获取发布数据

[英]PHP 7.x can't get post data using Ajax

After submitting the form I can't get post data, no clue where is the problem but I think it's the js file. 提交表单后,我无法获取帖子数据,不知道问题出在哪里,但我认为这是js文件。 I'm not advanced in using Ajax so I guess this is the problem. 我在使用Ajax方面并不先进,所以我想这就是问题所在。

I'm getting error that can't get $name, $projectFile etc. 我收到无法获得$name, $projectFile等的$name, $projectFile

So should I rewrite the js or PHP? 那么我应该重写js还是PHP? There are no syntax errors, I want this form to be dynamically submitted with Ajax. 没有语法错误,我希望此表单与Ajax动态提交。

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

<?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');
    }
}

i think you have to remove the contentType argument (and use serializeArray from your Form jQuery Object): 我认为您必须删除contentType参数(并从Form jQuery Object中使用serializeArray ):

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

        }
    });

Convert form fields to key value page and then pass that as the data in AJAX. 将表单字段转换为键值页面,然后将其作为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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM