I\'m trying to create a form that allows a user to fill out data and if an option is checked a div opens up and the user has the option to upload a file along with their sub
var formData = new FormData($("#formid")[0]);
$.ajax({
url:'url',
type: 'POST',
data: formData,
processData: false,
contentType: false,
async: false,
success:function(response){
if(response == '100'){
swal({
title: "Blog Added",
text: "Blog Added Successfully",
type: "success",
confirmButtonText: "OK",
showCancelButton: false,
}, function(){
/*location.reload();*/
window.location.href = 'redirect link';
});
}else{
toastr.error(response);
}
}
});
There are two ways to do it, one is pass parameters if you have less variables in you form..
$post('url',{param1:$("#name").val(),param2:$("#middle").val()},function(data){
//Action as per data returned from php code
});
Another method is serialize() method.
$post('url',{param1:$("form").serialize()},function(data){
//Action as per data returned from php code
});
you can do this using FormData. try this
$("form#data").submit(function() {
var formData = new FormData($(this)[0]);
$.post($(this).attr("action"), formData, function(data) {
alert(data);
});
return false;
});
// HTML
<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>
You'll need to store the file as FormData. You can still send the form data along with your file attachment by append your form data to the FormData object See below example:
NOTE: This example is assuming it's an xml file. If it's not an xml file, don't use the xml portion (last 3 lines in the if statement).
JavaScript
// #fileUpload is to a input element of the type file
var file = $('#fileUpload')[0].files[0]
var fd = new FormData();
fd.append('theFile', file);
$.ajax({
url: '...',
type: 'POST',
processData: false,
contentType: false,
data: fd,
success: function (data, status, jqxhr) {
//success code
},
error: function (jqxhr, status, msg) {
//error code
}
});
C#
protected void Page_Load(object sender, EventArgs e)
{
try
{
foreach (string file in Request.Files)
{
var fileContent = Request.Files[file];
if (fileContent != null && fileContent.ContentLength > 0)
{
Stream stream = fileContent.InputStream;
BinaryReader br = new BinaryReader(stream);
byte[] binaryData = br.ReadBytes(fileContent.ContentLength);
string xml = System.Text.Encoding.Default.GetString(binaryData);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
}
}
}
catch (Exception ex)
{
}
}