25

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);
}
5
  • Not possible via Ajax.
    – Linga
    Commented Aug 26, 2014 at 11:53
  • @ling.s actually you can with html5 file API
    – code-jaff
    Commented Aug 26, 2014 at 12:05
  • @code-jaff is OP using that API?
    – Linga
    Commented Aug 26, 2014 at 12:09
  • @ling.s obviously, since accessing the file from the files array.
    – code-jaff
    Commented Aug 26, 2014 at 12:28
  • You can find this perfect solution at github.com/kamleshwebtech/upload-image-by-ajax
    – Kamlesh
    Commented Sep 11, 2019 at 14:01

4 Answers 4

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.

1
  • 5
    better if you put an explanation how this would solve the issue
    – code-jaff
    Commented Aug 26, 2014 at 12:34
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';
2
  • We can't process files via ajax.
    – Linga
    Commented Aug 26, 2014 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. Commented May 19, 2017 at 14:48
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);
    }
});
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.....

2
  • 1
    You forgot to mention that ajaxSubmit is a jQuery plugin
    – baldrs
    Commented Aug 26, 2014 at 12:29
  • Yes I also think that ajaxSubmit can be used. :)
    – Majeed
    Commented Aug 26, 2014 at 13:00

Not the answer you're looking for? Browse other questions tagged or ask your own question.