Pass an image through AJAX

This question already has an answer here:

  • How can I upload files asynchronously? 27 answers

  • $.ajax({
        type: "POST",
        url: pathname,
        data: new FormData($('#devis')[0]),
        processData: false,
        contentType: false,
        success: function (data) {
            $("#divider").html(data);
        }
    });
    

    并在$_FILES[];正常获取文件数据$_FILES[];


    can you try it

    <script type="text/javascript">
    $(document).ready(function() {
    $("#submit").click(function() {
      var fileInput = document.getElementById('image_input_field');
      var file = fileInput.files[0];
      var formData = new FormData();
      formData.append('file', file);
      // console.log(file);
    
      var societe = $("input#societe").val();
      var message = $("textarea#message").val();
    
          $.ajax({
            url: "ajax.php",
            type: "POST",
            data: "file="+file,
            cache: false,
    
            success: function(reponse) {
              if(reponse) {
                alert(reponse);
    
                // console.log(reponse);
                // $('#devis').trigger("reset");
              } else {
                alert('Erreur');
              }
            }
          });
     }); });
    </script>
    

    In ajax.php

    just write

     echo 'something';
    

    As you may know already, it is not possible to process file uploads via ajax calls, it will be possible once HTML5 FILE I/O Api is ready and implemented by major browsers.

    You can use jQuery iframe post form plugin to post data in iframe so user experience will be similar to ajax call (partial update of page).

    Here is the link: https://github.com/dogzworld/iframe-post-form

    Description: "This jQuery ajax upload plugin creates a hidden iframe and sets the form's target attribute to post to that iframe. When the form is submitted, it is posted (including the file uploads) to the hidden iframe. Finally, the plugin collects the server's response from the iframe."

    As mentioned you can send response from the server and display updates on your webpage accordingly. There has to be a demo page but it is not working as of now.

    You can also use it for file uploads.

    Calling Example:

    jQuery('#frmId').iframePostForm({
        json : true,
        post : function () {
            //return true or false
            return true;
        },
        complete : function (response) {
            //complete event
            console.log(response);
        }
    });
    
    链接地址: http://www.djcxy.com/p/19602.html

    上一篇: 使用ajax将表单数据和文件传递给php

    下一篇: 通过AJAX传递图片