Uploading both data and files in one form using Ajax?

后端 未结 10 823
无人共我
无人共我 2020-11-21 05:48

I\'m using jQuery and Ajax for my forms to submit data and files but I\'m not sure how to send both data and files in one form?

I currently do almost the same with b

相关标签:
10条回答
  • 2020-11-21 06:23
    <form id="form" method="post" action="otherpage.php" 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 type='button' id='submit_btn'>Submit</button>
    </form>
    
    <script>
    $(document).on("click", "#submit_btn", function (e) {
        //Prevent Instant Click  
        e.preventDefault();
        // Create an FormData object 
        var formData = $("#form").submit(function (e) {
            return;
        });
        //formData[0] contain form data only 
        // You can directly make object via using form id but it require all ajax operation inside $("form").submit(<!-- Ajax Here   -->)
        var formData = new FormData(formData[0]);
        $.ajax({
            url: $('#form').attr('action'),
            type: 'POST',
            data: formData,
            success: function (response) {
                console.log(response);
            },
            contentType: false,
            processData: false,
            cache: false
        });
        return false;
    });
    </script>
    
    

    ///// otherpage.php

    <?php
        print_r($_FILES);
    ?>
    
    0 讨论(0)
  • 2020-11-21 06:25

    you can just append them on your formdata, add your files and datas in it.you can read this..

    https://developer.mozilla.org/en-US/docs/Web/API/FormData/append

    for better understanding. you can separately retrieve them $_FILES for your files and $_POST for your data.

    0 讨论(0)
  • 2020-11-21 06:27

    Or shorter:

    $("form#data").submit(function() {
        var formData = new FormData(this);
        $.post($(this).attr("action"), formData, function() {
            // success    
        });
        return false;
    });
    
    0 讨论(0)
  • 2020-11-21 06:30

    The problem I had was using the wrong jQuery identifier.

    You can upload data and files with one form using ajax.

    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>Submit</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
        });
    });
    

    Short Version

    $("form#data").submit(function(e) {
        e.preventDefault();
        var formData = new FormData(this);    
    
        $.post($(this).attr("action"), formData, function(data) {
            alert(data);
        });
    });
    
    0 讨论(0)
  • 2020-11-21 06:31

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

    you may try this (it uses jQuery):

    function ajax_form($form, on_complete)
    {
        var iframe;
    
        if (!$form.attr('target'))
        {
            //create a unique iframe for the form
            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 ()
            {
                //get the server response
                var response = iframe.contents().find('body').text();
                on_complete(response);
            });
        }
    }
    

    it works well with all browsers, you don't need to serialize or prepare the data. one down side is that you can't monitor the progress.

    also, at least for chrome, the request will not appear in the "xhr" tab of the developer tools but under "doc"

    0 讨论(0)
  • 2020-11-21 06:35

    For me following code work

    $(function () {
        debugger;
        document.getElementById("FormId").addEventListener("submit", function (e) {
            debugger;
            if (ValidDateFrom()) { // Check Validation 
                var form = e.target;
                if (form.getAttribute("enctype") === "multipart/form-data") {
                    debugger;
                    if (form.dataset.ajax) {
                        e.preventDefault();
                        e.stopImmediatePropagation();
                        var xhr = new XMLHttpRequest();
                        xhr.open(form.method, form.action);
                        xhr.onreadystatechange = function (result) {
                            debugger;
                            if (xhr.readyState == 4 && xhr.status == 200) {
                                debugger;
                                var responseData = JSON.parse(xhr.responseText);
                                SuccessMethod(responseData); // Redirect to your Success method 
                            }
                        };
                        xhr.send(new FormData(form));
                    }
                }
            }
        }, true);
    });
    

    In your Action Post Method, pass parameter as HttpPostedFileBase UploadFile and make sure your file input has same as mentioned in your parameter of the Action Method. It should work with AJAX Begin form as well.

    Remember over here that your AJAX BEGIN Form will not work over here since you make your post call defined in the code mentioned above and you can reference your method in the code as per the Requirement

    I know I am answering late but this is what worked for me

    0 讨论(0)
提交回复
热议问题