13

For past few days i have been struggling to submit a form with jQuery and AJAX. The problem i'm facing is to upload the image in the form field.

My form is something like this:

<form action="#" method="GET" role="form" enctype="multipart/form-data">
 <input type="text" placeholder="Name" name="name">
 <input type="file" name="img" multiple>
  <button type="submit">Submit </button>
</form>

and my jQuery script for getting the form value is something like this:

 $("form").submit(function (event) {
            $.dataArray = $(this).serializeArray(); // array of form data
            console.log($.dataArray);
            event.preventDefault();
        });

But this returns all the field values except image one, in case of image is return null.

How do I store in the dataarray?

I want to store so I can send the value to the server through the AJAX.

Luke Girvin
  • 13,221
  • 9
  • 64
  • 84
Racoon
  • 359
  • 1
  • 3
  • 14
  • Is there a reason why you want to store the values of your `form` into your `$.dataArray` variable in the first place? – Marylyn Lajato May 31 '17 at 11:52
  • Possible duplicate of [How can I upload files asynchronously?](https://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously) – prasanth May 31 '17 at 11:54
  • @eeya yes,so that i can pass the data to an api link through ajax along with other form content – Racoon Jun 01 '17 at 06:29
  • @Racoon: Have you found the answer you are looking for? – Marylyn Lajato Jun 01 '17 at 10:17
  • 1
    no. none of these seems to be working for my problem....i m still getting empty array but i m checking i will update as soon as i find the solution ty – Racoon Jun 04 '17 at 06:45

6 Answers6

19

For uploading single image its like this

     <html>
        <head>
            <meta charset="UTF-8">
            <title>AJAX image upload with, jQuery</title>
            <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
            <script type="text/javascript">
                $(document).ready(function (e) {
                    $('#upload').on('click', function () {
                        var file_data = $('#file').prop('files')[0];
                        var form_data = new FormData();
                        form_data.append('file', file_data);
                        $.ajax({
                            url: 'http://localhost/ci/index.php/welcome/upload', // point to server-side controller method
                            dataType: 'text', // what to expect back from the server
                            cache: false,
                            contentType: false,
                            processData: false,
                            data: form_data,
                            type: 'post',
                            success: function (response) {
                                $('#msg').html(response); // display success response from the server
                            },
                            error: function (response) {
                                $('#msg').html(response); // display error response from the server
                            }
                        });
                    });
                });
            </script>
        </head>
        <body>
            <p id="msg"></p>

            <input type="file" id="file" name="file" multiple />
            <button id="upload">Upload</button>
        </body>
    </html>

For multiple images u will have to loop its kinda different

Racoon
  • 359
  • 1
  • 3
  • 14
2

I have found a similar question, hope it will help you.

Upload image using jquery

Another option to consider is to use some sort of jQuery plugin to upload images like Cloudinary and include it in your HTML pages :

 <script src='jquery.min.js' type='text/javascript'></script>
 <script src='jquery.cloudinary.js' type='text/javascript'></script>

and then include all required jQuery files:

<script src='jquery.min.js' type='text/javascript'></script>
<script src='jquery.ui.widget.js' type='text/javascript'></script>
<script src='jquery.iframe-transport.js' type='text/javascript'></script>
<script src='jquery.fileupload.js' type='text/javascript'></script>
<script src='jquery.cloudinary.js' type='text/javascript'></script>
Dina Kaiser
  • 476
  • 3
  • 6
1

try this code, it's work for me.

 $("form").submit(function (event) {

    var form_data = new FormData($(this));

    $.ajax({
        url : url, 
        type : 'POST',
        data : form_data,
        processData: false,  // tell jQuery not to process the data
        contentType: false,
        success : function(resp){
        }
    });
});
Hitesh Vala Ahir
  • 773
  • 2
  • 13
  • 27
0

Try this code. using formData()

$("form").submit(function (event) {
            
    var formData = new FormData($(this));

    $.ajax({
          url: url,
          type: 'POST',
          data: formData,
          async: false,
          success: function (data) {
              //success callback
          },
          cache: false,
          contentType: false,
          processData: false
         });

   });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="GET" role="form" enctype="multipart/form-data">
 <input type="text" placeholder="Name" name="name">
 <input type="file" name="img" multiple>
  <button type="submit">Submit </button>
</form>
Dinesh undefined
  • 5,490
  • 2
  • 19
  • 40
0

serialize() method not able to post file data.

For sending file using ajax use FormData instead of serializing

HTML5 introduces FormData to allow developers to build forms objects dynamically, and then to send this form object via AJAX.

your Html

<form action="upload_image.php" id="form_img" method="GET" role="form" enctype="multipart/form-data">
 <input type="text" placeholder="Name" name="name">
 <input type="file" name="img" multiple>
  <button type="submit">Submit </button>
</form>

AJAX call

<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $("#form_img").submit(function(e){
            e.preventDefault();
            var formData = new FormData($("#form_img")[0]);

            $.ajax({
                url : $("#form_img").attr('action'),
                type : 'POST',
                data : formData,
                contentType : false,
                processData : false,
                success: function(resp) {
                    console.log(resp);                        
                }
            });
        });
    });

</script>

upload_image.php

print_r($_FILES) //check you get file data or not

Try this way.Hope it will help you

Nidhi
  • 1,529
  • 18
  • 28
0

Please check the follow the code, which i am using to upload image.

$.ajax({
            url: UPLOADURL,   // Url to which the request is send
            type: "POST",       // Type of request to be send, called as method
            data:  new FormData(this),// Data sent to server, a set of key/value pairs representing form fields and values
            contentType: false,// The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
            cache: false,// To unable request pages to be cached
            processData:false,// To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
            success: function(data)// A function to be called if request succeeds
            {

                data = JSON.parse(data);
                console.log(data);
                if(data.status == "Success"){
                    attachmentListing();
                    //$("#mailerMessage").html(data.data.mailStatus);
                    //$("#mailerMessage").fadeIn();
                    setTimeout(function () {
                        $("#mailerMessage").fadeOut();
                    },5000);
                }else{
                    toastr.warning(data.status);

                }
                $("#ajaxloader").addClass("hideajaxLoader");
            },
            error: function (jqXHR, errdata, errorThrown) {
                log("error");
                $("#ajaxloader").addClass("hideajaxLoader");
            }
        });