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.
jQuery AJAX image upload requires core jQuery features and nothing fancy is used. For AJAX image upload, enctype='multipart/form-data' is not required as we are not submitting via form post. We are using AJAX data transfer and multipart form data is not required for the image upload.
button('loading'); var data = $('#first-form'). serialize(); var formData = new FormData(); formdata. append("img", fileImage ); $. post("/Contractor/SendConfirmCode", data, function(result) { } else { } }, "json");
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With