Ajax Form Submit with attachment

独自空忆成欢 提交于 2019-12-13 20:54:09

问题


I have a Form on my Site thats submitted true ajax. This Form has a field where to attache .pdf files. How when submitting the form though the file is not send with the rest of data.

How can i get this to work? Here is my ajax code:

$('#submit_btn').click(function () {
                $.ajax({
                    type: 'POST',
                    url: '/contact.php',
                    dataType: "json",
                    data: $('#contactform').serialize(),
                    success: function (data) {

                        console.log(data.type);
                        console.log(data.msg);

                        var nClass = data.type;
                        var nTxt = data.msg;

                        $("#notice").attr('class', 'alert alert-' + nClass).text(nTxt).remove('hidden');
                        //reset fields if success
                        if (nClass != 'danger') {
                            $('#contactform input').val('');
                            $('#contactform textarea').val('');
                        }

                    }
                });
                return false;
            });

On the php side i have phpmailer setup and am handling the file so:

if(!empty($_FILES['file'])) {
            $_m->addAttachment($_FILES['file']['tmp_name'],$_FILES['file']['name']); 
        }  

回答1:


        $('#submit_btn').click(function () {
                    var formData = new FormData($('#contactform'));
                        $.ajax({
                            type: 'POST',
                            url: '/contact.php',
                           // dataType: "json",
                            data: formData ,
                      processData: false,
                        contentType: false,
                            success: function (data) {

                                console.log(data.type);
                                console.log(data.msg);

                                var nClass = data.type;
                                var nTxt = data.msg;

                                $("#notice").attr('class', 'alert alert-' + nClass).text(nTxt).remove('hidden');
                                //reset fields if success
                                if (nClass != 'danger') {
                                    $('#contactform input').val('');
                                    $('#contactform textarea').val('');
                                }

                            }
                        });
                        return false;
                    });


来源:https://stackoverflow.com/questions/31356084/ajax-form-submit-with-attachment

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!