14

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.

5
  • Is there a reason why you want to store the values of your form into your $.dataArray variable in the first place? Commented May 31, 2017 at 11:52
  • Possible duplicate of How can I upload files asynchronously? Commented May 31, 2017 at 11:54
  • @eeya yes,so that i can pass the data to an api link through ajax along with other form content Commented Jun 1, 2017 at 6:29
  • @Racoon: Have you found the answer you are looking for? Commented Jun 1, 2017 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 Commented Jun 4, 2017 at 6:45

6 Answers 6

21

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

Sign up to request clarification or add additional context in comments.

1 Comment

This is great- but i would have prefered using the naming in the question <input type="file" id="file_id" name="img" multiple> - here i dont know what files stand for in your code
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> 

Comments

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){ } }); }); 

Comments

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>

Comments

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

Comments

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"); } }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.