I am trying to develop an 'Add to cart' functionality in my PHP project. Here is the code.
This is the form from where I take the product data.
form
<form class="product-form" method="POST">
<input name="product_id" type="hidden"
value="<?=$data['id']?>">
<input name="user_id" type="hidden" value="1">
<button name="trending-submit" type="submit" class="btn btn-success">Add To
Cart</button>
</form>
ajax
$(".product-form").submit(function () {
var form_data = $(this).serialize();
var button_content = $(this).find("button[type=submit]");
button_content.html("Adding...");
$.ajax({
url: "./includes/add-to-cart.php",
type: "POST",
data: form_data,
dataType: "html",
success: function (response) {
alert(response);
$(".cart-quantity").html(response);
button_content.html("Add to Cart");
},
});
return false;
});
The "alert(response)" doesn't display anything at all.
The PHP code which calls cart object functions.
PHP
<?php
ob_start();
require("classes/Database.php");
$db = new Database();
require("classes/Cart.php");
$cart = new Cart($db);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ($_POST['product_id'] != null && $_POST['user_id'] != null) {
$cart->addToCart($_POST['product_id'], $_POST['user_id']);
}
$total = $cart->showCartQuantity();
echo $total;
exit;
}
You can't use relative paths with $.ajax(). You should instead use the URL (including FQDN) where you want to POST data.
Check your network tab in your browser and find the XHR request for more information.
Also, you should add e.preventDefault() to prevent the default behaviour of the HTML <form>, which is to refresh the page (ie. change the browser location to the URL specified in the HTML <form>'s action attribute).
$(".product-form").submit(function (e) {
e.preventDefault();
var form_data = $(this).serialize();
var button_content = $(this).find("button[type=submit]");
button_content.html("Adding...");
$.ajax({
url: "http://localhost/ajaxfile.php", // Full URL of PHP file
type: "POST",
data: form_data,
dataType: "html",
success: function (response) {
alert(response);
$(".cart-quantity").html(response);
button_content.html("Add to Cart");
},
});
return false;
});
i have problem pass data from selected file (image)
i will move the image to localhost directory
here my simple code
function uploadFile(){
event.preventDefault();
var input = document.getElementById("uploadImage");
file = input.files[0];
if(file != undefined){
formData= new FormData();
if(!!file.type.match(/image.*/)){
formData.append("image", file);
$.ajax({
url: "service.php?aksi=A",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(data){
alert('data);
}
});
}else{
alert('Not a valid image!');
}
}else{
alert('Input something!');
}
}
here my simple html code
<input type="file" required="" id="uploadImage" name="gambar" >
<button id="gantiphoto" name="submit" onclick="uploadFile()" class="btn btn-default">Upload </button>
and call it to specific php function
if ($_POST["aksi"]=="A"){
$dir = "asset/";
move_uploaded_file($_FILES["image"]["tmp_name"], $dir. $_FILES["image"]["name"]);
}
elseif ($_POST["aksi"]=="B"){
}
i try
$.ajax({
url: "service.php?aksi=A",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(data){
alert('data);
}
});
and
$.ajax({
url: "service.php",
type: "POST",
data: "aksi=A"+formData,
processData: false,
contentType: false,
success: function(data){
alert('data);
}
});
but the response still
Notice: Undefined index: image in C:\xampp\htdocs\rutela\service.php on line 166
or
Notice: Undefined index: aksi in C:\xampp\htdocs\rutela\service.php on line 7
i still dont understand how to pass this image file,. im success with text but cant solve this image pass data
im appreciate ur answer, im just newbie in ajax
You Can Add One More formData Filed
formData.append("aksi", "A");
Also Change Url to This
service.php
After This You Can Check Like
if($_POST['aksi'] == "A"){
$dir = "asset/";
move_uploaded_file($_FILES["image"]["tmp_name"], $dir. $_FILES["image"]["name"]);
}
else if($_POST['aksi'] == "B")
{
}
There are a couple things I might change to make this work:
<script>
function submitForm()
{
// Set error state a true
var valid = false;
// Init
var data1 = new FormData();
// Loop files
$.each($('input[type="file"]')[0].files, function(i, file) {
// If the file is good
if(!!file.type.match(/image.*/)) {
// Update status to valid
valid = true;
// Add file
data1.append(i, file);
}
});
// Do the ajax
if(!valid) {
$.ajax({
url: "service.php?aksi=A",
type: "POST",
data: data1,
enctype: 'multipart/form-data',
processData: false,
contentType: false,
success: function(response) {
$('#response').html(response);
}
});
}
else {
alert('Incorrect file type');
}
}
</script>
<div id="response"></div>
<input type="file" required="" id="uploadImage" name="gambar" >
<button id="gantiphoto" name="submit" onclick="submitForm()" class="btn btn-default">Upload</button>
In your PHP you should first try a test to make sure but I would switch to $_GET here not $_POST:
// ****** START TEST ******//
// If you do a test, you can see what is being sent so it will help you
// narrow down where it's going wrong
echo '<pre>'.print_r([
$_POST,
$_GET,
$_FILES
], 1).'</pre>';
// ****** START ACTUAL CODE ******//
// Stop if this is not set
if(empty($_GET["aksi"]))
die('aksi is a required parameter.');
// Switch to GET here
switch($_GET["aksi"]) {
case('A'):
if(empty($_FILES))
die('Invalid image.');
$dir = "asset/";
// I haven't checked, but I think these keys are numeric now
// The test above should tell you what they are exactly
move_uploaded_file($_FILES[0]["tmp_name"], $dir. $_FILES[0]["name"]);
break;
case('B'):
// do stuff
}
I'm using jQuery and Ajax for my forms to submit data and files but I'm not sure how to send both data and files in one form?
I currently do almost the same with both methods but the way in which the data is gathered into an array is different, the data uses .serialize(); but the files use = new FormData($(this)[0]);
Is it possible to combine both methods to be able to upload files and data in one form through Ajax?
Data jQuery, Ajax and html
$("form#data").submit(function(){
var formData = $(this).serialize();
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
<form id="data" method="post">
<input type="text" name="first" value="Bob" />
<input type="text" name="middle" value="James" />
<input type="text" name="last" value="Smith" />
<button>Submit</button>
</form>
Files jQuery, Ajax and html
$("form#files").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
<form id="files" method="post" enctype="multipart/form-data">
<input name="image" type="file" />
<button>Submit</button>
</form>
How can I combine the above so that I can send data and files in one form via Ajax?
My aim is to be able to send all of this form in one post with Ajax, is it possible?
<form id="datafiles" method="post" enctype="multipart/form-data">
<input type="text" name="first" value="Bob" />
<input type="text" name="middle" value="James" />
<input type="text" name="last" value="Smith" />
<input name="image" type="file" />
<button>Submit</button>
</form>
The problem I had was using the wrong jQuery identifier.
You can upload data and files with one form using ajax.
PHP + HTML
<?php
print_r($_POST);
print_r($_FILES);
?>
<form id="data" method="post" enctype="multipart/form-data">
<input type="text" name="first" value="Bob" />
<input type="text" name="middle" value="James" />
<input type="text" name="last" value="Smith" />
<input name="image" type="file" />
<button>Submit</button>
</form>
jQuery + Ajax
$("form#data").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
});
Short Version
$("form#data").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.post($(this).attr("action"), formData, function(data) {
alert(data);
});
});
another option is to use an iframe and set the form's target to it.
you may try this (it uses jQuery):
function ajax_form($form, on_complete)
{
var iframe;
if (!$form.attr('target'))
{
//create a unique iframe for the form
iframe = $("<iframe></iframe>").attr('name', 'ajax_form_' + Math.floor(Math.random() * 999999)).hide().appendTo($('body'));
$form.attr('target', iframe.attr('name'));
}
if (on_complete)
{
iframe = iframe || $('iframe[name="' + $form.attr('target') + '"]');
iframe.load(function ()
{
//get the server response
var response = iframe.contents().find('body').text();
on_complete(response);
});
}
}
it works well with all browsers, you don't need to serialize or prepare the data.
one down side is that you can't monitor the progress.
also, at least for chrome, the request will not appear in the "xhr" tab of the developer tools but under "doc"
I was having this same issue in ASP.Net MVC with HttpPostedFilebase and instead of using form on Submit I needed to use button on click where I needed to do some stuff and then if all OK the submit form so here is how I got it working
$(".submitbtn").on("click", function(e) {
var form = $("#Form");
// you can't pass Jquery form it has to be javascript form object
var formData = new FormData(form[0]);
//if you only need to upload files then
//Grab the File upload control and append each file manually to FormData
//var files = form.find("#fileupload")[0].files;
//$.each(files, function() {
// var file = $(this);
// formData.append(file[0].name, file[0]);
//});
if ($(form).valid()) {
$.ajax({
type: "POST",
url: $(form).prop("action"),
//dataType: 'json', //not sure but works for me without this
data: formData,
contentType: false, //this is requireded please see answers above
processData: false, //this is requireded please see answers above
//cache: false, //not sure but works for me without this
error : ErrorHandler,
success : successHandler
});
}
});
this will than correctly populate your MVC model, please make sure in your Model, The Property for HttpPostedFileBase[] has the same name as the Name of the input control in html i.e.
<input id="fileupload" type="file" name="UploadedFiles" multiple>
public class MyViewModel
{
public HttpPostedFileBase[] UploadedFiles { get; set; }
}
Or shorter:
$("form#data").submit(function() {
var formData = new FormData(this);
$.post($(this).attr("action"), formData, function() {
// success
});
return false;
});
EDIT: with the new version of JQuery (3.6), you could also try using contentType function argument instead of enctype. Try contentType: multipart/form-data.
For me, it didn't work without enctype: 'multipart/form-data' field in the Ajax request. I hope it helps someone who is stuck in a similar problem.
Even though the enctype was already set in the form attribute, for some reason, the Ajax request didn't automatically identify the enctype without explicit declaration (jQuery 3.3.1).
// Tested, this works for me (jQuery 3.3.1)
fileUploadForm.submit(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: $(this).attr('action'),
enctype: 'multipart/form-data',
data: new FormData(this),
processData: false,
contentType: false,
success: function (data) {
console.log('Thank God it worked!');
}
}
);
});
// enctype field was set in the form but Ajax request didn't set it by default.
<form action="process/file-upload" enctype="multipart/form-data" method="post" >
<input type="file" name="input-file" accept="text/plain" required>
...
</form>
As others mentioned above, please also pay special attention to the contentType and processData fields.
A Simple but more effective way:
new FormData() is itself like a container (or a bag). You can put everything attr or file in itself.
The only thing you'll need to append the attribute, file, fileName eg:
let formData = new FormData()
formData.append('input', input.files[0], input.files[0].name)
and just pass it in AJAX request. Eg:
let formData = new FormData()
var d = $('#fileid')[0].files[0]
formData.append('fileid', d);
formData.append('inputname', value);
$.ajax({
url: '/yourroute',
method: 'POST',
contentType: false,
processData: false,
data: formData,
success: function(res){
console.log('successfully')
},
error: function(){
console.log('error')
}
})
You can append n number of files or data with FormData.
and if you're making AJAX Request from Script.js file to Route file in Node.js beware of using
req.body to access data (ie text)
req.files to access file (ie image, video etc)
The code below works for me
$(function () {
debugger;
document.getElementById("FormId").addEventListener("submit", function (e) {
debugger;
if (ValidDateFrom()) { // Check Validation
var form = e.target;
if (form.getAttribute("enctype") === "multipart/form-data") {
debugger;
if (form.dataset.ajax) {
e.preventDefault();
e.stopImmediatePropagation();
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action);
xhr.onreadystatechange = function (result) {
debugger;
if (xhr.readyState == 4 && xhr.status == 200) {
debugger;
var responseData = JSON.parse(xhr.responseText);
SuccessMethod(responseData); // Redirect to your Success method
}
};
xhr.send(new FormData(form));
}
}
}
}, true);
});
In your Action Post Method, pass parameter as HttpPostedFileBase UploadFile and make sure your file input has same as mentioned in your parameter of the Action Method.
It should work with AJAX Begin form as well.
Remember over here that your AJAX BEGIN Form will not work over here since you make your post call defined in the code mentioned above and you can reference your method in the code as per the Requirement
I know I am answering late but this is what worked for me
Just to remind, in 2022 you don't need to use jquery. Try js standard Fetch API
var formData = new FormData(this);
fetch(url, {
method: 'POST',
body: formData
})
.then(response => {
if(response.ok) {
//success
alert(response);
} else {
throw Error('Server error');
}
})
.catch(error => {
console.log('fail', error);
});
This is a solution that I implemented
var formData = new FormData();
var files = $('input[type=file]');
for (var i = 0; i < files.length; i++) {
if (files[i].value == "" || files[i].value == null) {
return false;
}
else {
formData.append(files[i].name, files[i].files[0]);
}
}
var formSerializeArray = $("#Form").serializeArray();
for (var i = 0; i < formSerializeArray.length; i++) {
formData.append(formSerializeArray[i].name, formSerializeArray[i].value)
}
$.ajax({
type: 'POST',
data: formData,
contentType: false,
processData: false,
cache: false,
url: '/Controller/Action',
success: function (response) {
if (response.Success == true) {
return true;
}
else {
return false;
}
},
error: function () {
return false;
},
failure: function () {
return false;
}
});
---Solution for DOT NET CORE MVC Implementation---
While looking at this question I though I should right .NET CORE implementation for this because the question is not specific to any backend language.
So guys here is the standalone implementation example.
Objective :- To submit form fields including files and how we can get data in a single model at backend
HTML Code / View Code - Views/Home/Index.cshtml
#{
ViewData["Title"] = "Home Page";
}
<input type="file" id="FileUpload1" multiple />
<div>
<label>Enter First Name :</label>
<input type="text" id="nameText" maxlength="50" />
</div>
<input type="button" id="btnUpload" value="Submit Form with Files" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('#btnUpload').click(function () {
// Checking whether FormData is available in browser
if (window.FormData !== undefined) {
var fileUpload = $("#FileUpload1").get(0);
var files = fileUpload.files;
// Create FormData object
var fileData = new FormData();
// Looping over all files and add it to FormData object
for (var i = 0; i < files.length; i++) {
fileData.append("files", files[i]);
}
// Adding one more key to FormData object
fileData.append('FirstName', $("#nameText").val());
$.ajax({
url: '/Home/UploadFiles',
type: "POST",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: fileData,
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
} else {
alert("FormData is not supported.");
}
});
});
</script>
Backend Code / Controller action method Controllers/HomeController.cs
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly IWebHostEnvironment _environment;
public HomeController(ILogger<HomeController> logger, IWebHostEnvironment environment)
{
_logger = logger;
_environment = environment;
}
public IActionResult Index()
{
return View();
}
public IActionResult Privacy()
{
return View();
}
[HttpPost]
public async Task<IActionResult> UploadFiles(MyForm myForm)
{
var files = myForm.Files;
// First Name
string name = myForm.FirstName;
// check All files
foreach (IFormFile source in files)
{
string filename = ContentDispositionHeaderValue.Parse(source.ContentDisposition).FileName.Trim('"');
filename = this.EnsureCorrectFilename(filename);
string fileWithPath = this.GetPathAndFilename(filename);
// Create directory if not exist
Directory.CreateDirectory(Path.GetDirectoryName(fileWithPath));
using (FileStream output = System.IO.File.Create(fileWithPath))
await source.CopyToAsync(output);
}
return Ok("Success");
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
public class MyForm
{
public string FirstName { get; set; }
public IList<IFormFile> Files { get; set; }
}
private string EnsureCorrectFilename(string filename)
{
if (filename.Contains("\\"))
filename = filename.Substring(filename.LastIndexOf("\\") + 1);
return filename;
}
private string GetPathAndFilename(string filename)
{
return Path.Combine(_environment.ContentRootPath, "uploadedFiles", filename);
}
}
Full Source Code Repo: https://github.com/rj-learning/DotNetCoreFileUpload
In my case I had to make a POST request, which had information sent through the header, and also a file sent using a FormData object.
I made it work using a combination of some of the answers here, so basically what ended up working was having this five lines in my Ajax request:
contentType: "application/octet-stream",
enctype: 'multipart/form-data',
contentType: false,
processData: false,
data: formData,
Where formData was a variable created like this:
var file = document.getElementById('uploadedFile').files[0];
var form = $('form')[0];
var formData = new FormData(form);
formData.append("File", file);
you can just append them on your formdata, add your files and datas in it.you can read this..
https://developer.mozilla.org/en-US/docs/Web/API/FormData/append
for better understanding. you can separately retrieve them $_FILES for your files and $_POST for your data.
<form id="form" method="post" action="otherpage.php" enctype="multipart/form-data">
<input type="text" name="first" value="Bob" />
<input type="text" name="middle" value="James" />
<input type="text" name="last" value="Smith" />
<input name="image" type="file" />
<button type='button' id='submit_btn'>Submit</button>
</form>
<script>
$(document).on("click", "#submit_btn", function (e) {
//Prevent Instant Click
e.preventDefault();
// Create an FormData object
var formData = $("#form").submit(function (e) {
return;
});
//formData[0] contain form data only
// You can directly make object via using form id but it require all ajax operation inside $("form").submit(<!-- Ajax Here -->)
var formData = new FormData(formData[0]);
$.ajax({
url: $('#form').attr('action'),
type: 'POST',
data: formData,
success: function (response) {
console.log(response);
},
contentType: false,
processData: false,
cache: false
});
return false;
});
</script>
///// otherpage.php
<?php
print_r($_FILES);
?>
I'm trying to upload image on user registration via ajax. This is how it's look like the form + some fields for name, password and email which are working good.
<form method="post" class="registerForm" enctype="multipart/form-data" id="login-form">
<div class="form-group">
<label><b>Profile Image <span class="required">*</span></b></label>
<input accept="image/*" type="file" id="picture" name="picture" required>
</div>
<div class="clearfix">
<button type="submit" id="login" class="signupbtn">Sign Up</button>
</div>
</form>
I have found on another thread here on SO that I need to put this on my ajax script
var data = $("#login-form").serialize();
var form = new FormData(document.getElementById('picture'));
//append files
var file = document.getElementById('picture').files[0];
if (file) {
form.append('picture', file);
}
And this is whole ajax
function submitForm()
{
var data = $("#login-form").serialize();
var form = new FormData(document.getElementById('picture'));
//append files
var file = document.getElementById('picture').files[0];
if (file) {
form.append('picture', file);
}
$.ajax({
type : 'POST',
url : 'registration.php',
data : data,
beforeSend: function()
{
$("#error").fadeOut();
$("#login").html('<span class="glyphicon glyphicon-transfer"></span> sending ...');
},
success : function(data)
{
if(data=="registered")
{
}
}
});
return false;
}
And the server side for the picture part and the query
if(!empty($_FILES['picture']) && $_FILES['picture']['size'] >0 ){
$profilePic = $randomString. basename($_FILES['picture']['name']);
$uploadfile = $uploaddir .$randomString. basename($_FILES['picture']['name']);
if (move_uploaded_file($_FILES['picture']['tmp_name'], $uploadfile)) {
} else {
$error = "error\n";
}
}else{
$error ='Please add your Picture!';
}
var_dump($_FILES['picture']);
try
{
$stmt = $db_con->prepare("SELECT * FROM users WHERE email=:email");
$stmt->execute(array(":email"=>$email));
$count = $stmt->rowCount();
if($count==0){
$stmt = $db_con->prepare("INSERT INTO users (picture) VALUES (:picture)");
$stmt->bindParam(":picture",$profilePic);
if($stmt->execute()) {
echo "registered";
}
else { echo "Query could not execute !"; }
}
else{ echo "1"; }
}
catch(PDOException $e){
echo $e->getMessage();
}
I've removed other fields in order keep the code simple as much as possible. All fields got inserted and saved in database except the image name.
What can be the problem? No errors at all. I've got registered on the console and NULL for var_dump($_FILES['picture'])
jQuery processes the data as a string if you don't use proccessData: false. Bellow code will work just fine. Also included some comments in code
$(document).ready(function (e){
$("#login-form").on('submit',(function(e){
e.preventDefault();
$.ajax({
url: "registration.php",
type: "POST",
data: new FormData(this), // Data sent to server
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data){
if(data=="registered"){}
},
error: function(){}
});
}));
});
You must set the contentType option to false, so jQuery won't add a Content-Type heade also set processData flag set to false otherwise jQuery will try to convert your FormData into a string, which will fail.
So ajax code will look like
$(".signupbtn").click(function(e){
e.preventDefault();
var form = new FormData(document.getElementById('picture'));
//append files
var file = document.getElementById('picture').files[0];
if (file) {
form.append('picture', file);
}
$.ajax({
type : 'POST',
url : 'registration.php',
data : form,
contentType: false,
processData: false,
success : function(data){}
});
});
I'm sending formData through jQuery.ajax(), however the PHP function that is processing all this can't properly retrieve and recognize the DATA being sent. I've went through many questions on stackoverflow and also tried this in many different ways all to no avail and finally gave up.
This is all done in WORDPRESS.
I can't use serialize because I'm also sending files, but I left them out below for the sake of simplicity.
This is the simplified version of the form:
<form id="newForm" method="post" enctype='multipart/form-data'>
<div>
<label>Title</label>
<input name="title" type="text" value=""/>
</div>
<div>
<label>Content</label>
<input name="content" type="text" value=""/>
</div>
<button type="submit" id="submit_button">SUBMIT</button>
</form>
This is the jQuery:
jQuery(document).ready(function(){
$('#newForm').submit(function(e){
e.preventDefault();
var new_data = new FormData($(this)[0]);
$.ajax({
url:ajaxurl,
type: "POST",
data: {
'action': 'upload_function',
new_data //I've tried new_data: new_data
},
cache:false,
processData:false,
dataType: 'json', //tried not sending it as json dataType, still didn't work
success:function(response){
console.log(response);
if(response.success == 1){
alert("Post inserted");
}else{
alert("Post not inserted");
}
},
error:function(){
alert("Ajax request hasn't passed");
}
});
});
});
This is the PHP that handles the post insert(it's getting called properly, I've checked by inserting static values in post title and content), I left out the nonce and other stuff for the sake of simplicity:
function upload_function(){
$json_result=array();
$json_input=$_POST['new_data'];
$post_vars=json_decode($json_input,true);
$submit_post_data = array (
'post_title' => $post_vars['title'],
'post_content' => $post_vars['content'],
'post_status' => 'draft'
);
$post_id = wp_insert_post($submit_post_data);
if($post_id){
$json_result['success']=1;
}else{
$json_result['success']=0;
}
wp_send_json($json_result);
exit();
}
add_action('wp_ajax_upload_function','upload_function');
you need to serialize the form data and then pass it to the php code. Do this to your var new_data assignment.
var new_data = $(this).serialize()
EDIT 1: As you stated you have files you need use FormData object to pass the files to sever in ajax. refer the code below.
var $element = $(this);
var formdata = new FormData();
var totalFiles = $element.files.length;
if (totalFiles > 0) {
for (var i = 0; i < totalFiles; i++) {
var file = $element.files[i];
formdata.append("FileUpload", file);
}
$.ajax({
type: "POST",
url: Url,
data: formdata,
contentType: false,
processData: false,
success: function (result) {
// make the server return a array of file names that has been saved.
//Post your other form elements data a this point with the filename array.
},
error: function (error) {
console.log("File Upload Failure");
}
});
}