wordpress ajax表单提交附件

时间:2016-02-12 12:08:11

标签: php ajax wordpress

我试图从自制的插件wordpress表单发布数据。我可以使用 form.serialize()成功发送表单字段数据,但是遗漏了文件输入的内容。所以我尝试了替代方案按照tutorial创建 formdata 然而,当我使用formdata而不是form.serialize时,我收到404错误。 This answer by Nithin on SO seemed to get the same problem as indicated by jon dhano

PHP

<form action="{get_permalink()}" id="app" method="post">
    <p class="name">
        <input name="name" type="text" class="validate[required,custom[onlyLetter],length[0,100]] feedback-input" placeholder="Your Name" id="name">
    </p>
    <p class="email">
        <input name="email" type="text" class="validate[required,custom[email]] feedback-input" id="email" placeholder="Your Email">
    </p>
    <p class="investment">
        <input name="investment" type="text" class="validate[required,custom[integer]] feedback-input" id="investment" placeholder="Your Investment ID">
    </p>
    <h2 class="file-header">Files Upload</h2>
    <p class="files">
        <span class="file-label">File [1]</span>
        <input name="file1" type="file" class="files-upload" id="file1">
    </p>
    <p class="files">
        <span class="file-label">File [2]</span>
        <input name="file2" type="file" class="files-upload" id="file2">
    </p>
    <p class="files">
        <span class="file-label">File [3]</span>
        <input name="file3" type="file" class="files-upload" id="file3">
    </p>
    <p class="files">
        <span class="file-label">File [4]</span>
        <input name="file4" type="file" class="files-upload" id="file4">
    </p>
    <div class="submit">
        <button type="submit" id="button-blue" name="">Submit</button>
        <div class="ease">
        </div>
    </div>
    <input type="hidden" name="application_form_submitted" value="1">
</form>

JS

(function($){
    $('#button-blue').click(function(e){
        e.preventDefault();
        var m_data = new FormData();
        m_data.append( 'name', $('input[name=name]').val());
        m_data.append( 'email', $('input[name=email]').val());
        m_data.append( 'investment', $('input[name=investment]').val());
        m_data.append( 'file1', $('input[name=file1]')[0].files[0]);
        m_data.append( 'file2', $('input[name=file2]')[0].files[0]);
        m_data.append( 'file3', $('input[name=file3]')[0].files[0]);
        m_data.append( 'file4', $('input[name=file4]')[0].files[0]);

        $.ajax({
            url: $('#app').attr('action'),
            data: m_data,
            processData: false,
            contentType: false,
            type: 'POST',
            dataType:'json',
            success: function (d) {
                var d = JSON.parse(d);
                alert(d.text);
            },
            error: function (xhr, textStatus, error) {
                alert(error);
            }
        });
    });
})( jQuery );

0 个答案:

没有答案