search

Home  >  Q&A  >  body text

How to use Ajax to upload data and files at the same time?

<p>I'm using jQuery and Ajax to submit data and files, but I'm not sure how to send both data and files in one form? </p> <p>I currently use both methods in almost the same way, but the way of collecting the data into an array is different, data uses <code>.serialize();</code> and files uses <code> ;= new FormData($(this)[0]);</code></p> <p>Is it possible to combine these two methods to upload files and data in one form via Ajax? </p> <p><strong>Data jQuery, Ajax and html</strong></p> <pre class="brush:php;toolbar:false;">$("form#data").submit(function(){ var formData = $(this).serialize(); $.ajax({ url: window.location.pathname, type: 'POST', data: formData, async: false, success: function (data) { alert(data) }, cache: false, contentType: false, processData: false }); return false; }); <form id="data" method="post"> <input type="text" name="first" value="Bob" /> <input type="text" name="middle" value="James" /> <input type="text" name="last" value="Smith" /> <button>Submit</button> </form></pre> <p><strong>Documentation jQuery, Ajax and html</strong></p> <pre class="brush:php;toolbar:false;">$("form#files").submit(function(){ var formData = new FormData($(this)[0]); $.ajax({ url: window.location.pathname, type: 'POST', data: formData, async: false, success: function (data) { alert(data) }, cache: false, contentType: false, processData: false }); return false; }); <form id="files" method="post" enctype="multipart/form-data"> <input name="image" type="file" /> <button>Submit</button> </form></pre> <p>How can I combine the above so that I can send data and files in one form via Ajax? </p> <p>My goal is to be able to send all these forms together via Ajax, is this possible?</p> <pre class="brush:php;toolbar:false;"><form id="datafiles" method="post" enctype="multipart/form-data"> <input type="text" name="first" value="Bob" /> <input type="text" name="middle" value="James" /> <input type="text" name="last" value="Smith" /> <input name="image" type="file" /> <button>提交</button> </form></pre> <p><br /></p>
P粉012875927P粉012875927491 days ago755

reply all(2)I'll reply

  • P粉794177659

    P粉7941776592023-08-21 09:06:07

    Another option is to use an iframe and set the form's target to it.

    You can try this (it uses jQuery):

    function ajax_form($form, on_complete)
    {
        var iframe;
    
        if (!$form.attr('target'))
        {
            //为表单创建一个唯一的iframe
            iframe = $("<iframe></iframe>").attr('name', 'ajax_form_' + Math.floor(Math.random() * 999999)).hide().appendTo($('body'));
            $form.attr('target', iframe.attr('name'));
        }
    
        if (on_complete)
        {
            iframe = iframe || $('iframe[name="' + $form.attr('target') + '"]');
            iframe.load(function ()
            {
                //获取服务器响应
                var response = iframe.contents().find('body').text();
                on_complete(response);
            });
        }
    }

    It works in all browsers, you don't need to serialize or prepare the data. One drawback is that you can't monitor progress.

    Also, at least for Chrome, the request does not appear under the "xhr" tab of the developer tools, but under "doc".

    reply
    0
  • P粉064448449

    P粉0644484492023-08-21 00:11:35

    The problem I had was using the wrong jQuery identifier.

    You can use a formUse ajax to upload data and files.

    PHP HTML

    <?php
    
    print_r($_POST);
    print_r($_FILES);
    ?>
    
    <form id="data" method="post" enctype="multipart/form-data">
        <input type="text" name="first" value="Bob" />
        <input type="text" name="middle" value="James" />
        <input type="text" name="last" value="Smith" />
        <input name="image" type="file" />
        <button>提交</button>
    </form>

    jQuery Ajax

    $("form#data").submit(function(e) {
        e.preventDefault();    
        var formData = new FormData(this);
    
        $.ajax({
            url: window.location.pathname,
            type: 'POST',
            data: formData,
            success: function (data) {
                alert(data)
            },
            cache: false,
            contentType: false,
            processData: false
        });
    });

    Simplified version

    $("form#data").submit(function(e) {
        e.preventDefault();
        var formData = new FormData(this);    
    
        $.post($(this).attr("action"), formData, function(data) {
            alert(data);
        });
    });

    reply
    0
  • Cancelreply