简体   繁体   English

使用ajax发布文件和数据

[英]Post File and data with ajax

I have read in other post on SO, similar to what is happening to me, but I still can not get the solution 我在其他帖子中读过SO,类似于我发生的事情,但我仍然无法得到解决方案

$('#edit-continue').on('click', function(e) {
    e.preventDefault();
    var photo = new FormData();                               <-----
    jQuery.each(jQuery('#photo')[0].files, function(i, file) {<----- SO suggest for file upload
        photo.append('file-' + i, file);                      <-----
    });
    $.ajax({
        type: "POST",
        url: "/templates/staycation/common/edit-profile.php",
        data: {
            id: $('#id').val(),
            email: $('#email').val(),
            birthday: $('#birthday').val(),
            gender: $("input[name='gender']:checked").val(),
            photo: photo,
        },
        success: function(data) {
            console.log('pass');
            console.log(data);
        },
        error: function(data) {
            console.log('not pass');
            console.log(data);
        },
        cache: false,
        contentType: false,
        processData: false, <------ i think my error is here
    });

if i leave processData: false, , the post arrives empty, by making echo of my array, all data is empty, in the other case, if I comment, the console throws Uncaught TypeError: Illegal invocation 如果我离开processData: false,帖子到空了,通过回显我的数组,所有数据都是空的,在另一种情况下,如果我发表评论,控制台抛出Uncaught TypeError: Illegal invocation

I need to do is send the values entered by the user such as "email", "gender", ... and profile picture, to make an update to the database and to save the image to a folder 我需要做的是发送用户输入的值,如“email”,“gender”,...和个人资料图片,以更新数据库并将图像保存到文件夹

this is what working perfectly for me 这对我来说非常合适

// formData will wrap all files and content of form
var formData=new FormData($('#formId')[0]); 
// you can add more data ot formData after this to
$.ajax({
        url     :   'upload.php',
        type    :   'post',
        data    :   formData,
        processData:false,
        contentType:false,
        success :   function(e)
                    {
                        alert('uploaded successfully');
                    },
        error   :   function()
                    {
                        alert('hello from here');   
                    }
    });

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

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