简体   繁体   中英

Send data to PHP with ajax using formdata

SOLUTION: I had to drop the sumbmit button and use a regular button. The rest of this code works. I also dropped the HTML form.

I'm trying to send an image + some text to my php script with ajax using formdata. This is what i got:

$ajax_uploadImage = function (form)
{
    var data = new FormData();

    data.append('title', form.find('#title').val());
    data.append('comment', form.find('#comment').val());
    data.append('image', form.find('#image').prop('files')[0]);

    $.ajax({
        url: '../php/upload_image.php',
        data: data,
        type: 'POST',
        processData: false,
        contentType: false,
        success: function (data) {
            alert('something');
        }
    });
}

The form in the function parameters is a normal html form, here is the form in html:

<form enctype="multipart/form-data" id="upload_image">
    <label for="title">Title:</label>
        <input type="text" id="title" name="title" />
    <br />

    <label for="comment">Comment:</label>
    <input type="text" id="comment" name="comment" />
    <br />

    <label for="image">Image:</label>
    <input type="file" id="image" name="image" />
    <br />

    <input type="submit" value="Upload picture" name="submit">
    <hr />
</form>

The alert in success never triggers, can anyone help?

EDIT: Adding the PHP, even though it doesn't do anything:

<?php echo 'something'; ?>

Right now you are storing a jQuery object in the FormData which cannot work. Use the values of those elements instead. In case of the file input you need to use the File object in the files property of the DOM element:

data.append('title', form.find('#title').val());
data.append('comment', form.find('#comment').val());
data.append('image', form.find('#image').prop('files')[0]);

尝试添加表单操作,例如:

<form enctype="multipart/form-data" id="upload_image" action="upload_image.php">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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