最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Send image and text with ajax - Stack Overflow

programmeradmin6浏览0评论

I'm using javascript's 'formData' to send image files with ajax. How can I attach other data to formData, for example a text string?

JS:

$("#post-image").click(function(){
    $.ajax({
        url: "../../build/ajaxes/upload-photo.php",
        type: "POST",
        data: formdata,
        processData: false,
        contentType: false,
        success: function (response) {
            console.log(response);
        }
    });
});

PHP:

In my PHP I can access the image by using $_FILES["images"]. I don't know what to use for my additional data passed with formdata.

I'm using javascript's 'formData' to send image files with ajax. How can I attach other data to formData, for example a text string?

JS:

$("#post-image").click(function(){
    $.ajax({
        url: "../../build/ajaxes/upload-photo.php",
        type: "POST",
        data: formdata,
        processData: false,
        contentType: false,
        success: function (response) {
            console.log(response);
        }
    });
});

PHP:

In my PHP I can access the image by using $_FILES["images"]. I don't know what to use for my additional data passed with formdata.

Share asked Dec 9, 2012 at 21:49 Don PDon P 63.9k121 gold badges318 silver badges449 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

If you want to add parameters to FormData use FormData.append

$("#post-image").click(function(){
    formdata.append('name', 'value');
    $.ajax({
        url: "../../build/ajaxes/upload-photo.php",
        type: "POST",
        data: formdata,
        processData: false,
        contentType: false,
        success: function (response) {
            console.log(response);
        }
    });
});

In PHP use $_POST["name"] to get the value.

You need to submit the form as multipart. Here's a SO solution to your question: Making an HTTP POST call with multipart/form-data using jQuery?

Not an exact duplicate, so I didn't mark it as such, but it's a direct reference to the solution to your problem.

Edit: you'll notice that some of the answers reference FormData as a solution as well. Once you get the data posting properly, you can then access it with the normal $_FORM collection in PHP.

If you have Big form with Multiple file uploads then not use MALSUP JQUERY PLUGIN .It will send all your form fields with just

  $(form).ajaxSubmit();    
发布评论

评论列表(0)

  1. 暂无评论