24

Basically I want to pass a image file with ajax on submitting a form and retrieve the image and send it by email as an attachment file:

Here's the form :

<form role="form" action="" name="devis" id="devis" method="post" enctype="multipart/form-data" class="form-horizontal">
    <fieldset>
        <div class="form-group">
            <label class="control-label col-md-4" for="societe">Company</label>
            <div class="col-md-8">
                <input type="text" class="form-control input-md col-md-8" name="societe" value="" maxlength="" id="societe">
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-md-4" for="message"><span class="required">* </span>Message</label>
            <div class="col-md-8">
                <textarea rows="5" name="message" class="form-control input-md col-md-8" maxlength="" required="" style="resize:none;" id="message"></textarea>
            </div>
        </div>
        <div class="form-group" id="input_file">
            <label class="control-label col-md-4" for="image_input_field">Logo</label>
            <div class="col-md-8">
            <div class="input-group uploaddiv">
                <span class="input-group-btn">
                    <span class="btn btn-default btn-file">
                        Parcourir <input type="file" id="image_input_field" name="file">
                    </span>
                </span>
                <input type="text" class="form-control" readonly="">
            </div>
            </div>
        </div>
    <div class="form-group">
    <div class="form-actions col-md-9 col-md-offset-3 text-right">
        <input type="submit" value="Envoyer" name="" class="btn btn-primary" id="submit">
        <input type="reset" value="Annuler" name="" class="btn btn-default" id="reset">
        </div>
    </div>
    </fieldset>
</form>

I can't seem to find what's the error in my code ! Here's the AJAX call :

jQuery(document).on("click", "#submit", function(e) {
      e.preventDefault();
      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();
      jQuery.ajax({
        url: "ajax.php",
        type: "post",
        data: {
           'file': file,
           'module' : 'ajax_data_form',
           'societe': societe,
           'message': message
        },
        cache: false,

        success: function(reponse) {
          if(reponse) {
            alert(reponse);
            // console.log(reponse);
            // jQuery('#devis').trigger("reset");
          } else {
            alert('Erreur');
          }
        }
      });
     });

And here's the ajax.php:

<?php
if( isset($_POST['module']) && $_POST['module'] == "ajax_data_form" )
{
     var_dump($_FILES);
}
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
user3350731
  • 962
  • 1
  • 10
  • 30

4 Answers4

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

and get the file data normally in $_FILES[];. Because FormData is automatically handles the multipart header in an ajax request.

Karthikeyan Ganesan
  • 1,901
  • 20
  • 23
2

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';
Punitha Subramani
  • 1,467
  • 1
  • 8
  • 6
  • We can't process files via ajax. – Linga Aug 26 '14 at 11:55
  • 2
    Everybody saying you can´t process files via ajax... I always convert the file to base64 string and send it via ajax call. On the server side, you receive the string and write it to disk. It can be done and it´s simple enough. – Curious Mind May 19 '17 at 14:48
0

Using a Jquery Plugin Called Jquery Form plugin Link

I would suggest to simply submit the form using jquery and what ever data you want you can keep them in hidden fields.

$("#devis").ajaxSubmit(options); 
return false;

The you can easily get the file in the php page like this

$ImageTempname  = $_FILES['ImageFile']['tmp_name'];
$ImageFilename  = $_FILES['ImageFile']['name'];
$ImageType      = $_FILES['ImageFile']['type'];

and so on.....

M H
  • 2,179
  • 25
  • 50
Yunus Aslam
  • 2,447
  • 4
  • 25
  • 39
0

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);
    }
});
Dharmang
  • 3,018
  • 35
  • 38