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 submission.
The issue I am having is getting the file to pass thru ajax correct. I can't quite mesh it together properly to get the results that I am looking for which is the file posting to my php script. Here's my code for passing the data:
$(document).ready(function() {
$("#submit_btn").click(function() {
var proceed = true;
//simple validation at client's end
//loop through each field and we simply change border color to red for invalid fields
$("#contact_form input[required=true], #contact_form textarea[required=true]").each(function(){
$(this).css('border-color','');
if(!$.trim($(this).val())){ //if this field is empty
$(this).css('border-color','red'); //change border color to red
proceed = false; //set do not proceed flag
}
//check invalid email
var email_reg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
if($(this).attr("type")=="email" && !email_reg.test($.trim($(this).val()))){
$(this).css('border-color','red'); //change border color to red
proceed = false; //set do not proceed flag
}
});
if(proceed) //everything looks good! proceed...
{
//get input field values data to be sent to server
var search_array = $('input[name="donation"]').map(function(){
return $(this).val();
}).get();
post_data = {
'user_name' : $('input[name=full_name]').val(),
'user_email' : $('input[name=email]').val(),
'address' : $('input[name=address]').val(),
'address2' : $('input[name=address2]').val(),
'city' : $('input[name=city]').val(),
'state' : $('input[name=state]').val(),
'zip' : $('input[name=zip]').val(),
'ccnum' : $('input[name=ccnum]').val(),
'expmonth' : $('select[name=expmonth]').val(),
'expyear' : $('select[name=expyear]').val(),
'cardname' : $('input[name=cardname]').val(),
'ccvcode' : $('input[name=ccvcode]').val(),
'donation' : $('input[name=donation]:checked').val(),
'donation_other' : $('input[name=donation_other]').val(),
'contact_phone' : $('input[name=contact_phone]').val(),
'attached_file' : $('input[name=attached_file]').val(),
'donatecomments' : $('textarea[name=donatecomments]').val()
};
//Ajax post data to server
$.post('.php', post_data, function(response){
if(response.type == 'error'){ //load json data from server and output message
output = '<div class="error">'+response.text+'</div>';
}else{
output = '<div class="success">'+response.text+'</div>';
//reset values in all input fields
$("#contact_form input[required=true], #contact_form textarea[required=true]").val('');
$("#contact_form #contact_body").slideUp(); //hide form after success
window.top.location.href = "";
}
$("#contact_form #contact_results").hide().html(output).slideDown();
}, 'json');
}
});
//reset previously set border colors and hide all message on .keyup()
$("#contact_form input[required=true], #contact_form textarea[required=true]").keyup(function() {
$(this).css('border-color','');
$("#result").slideUp();
});
});
And my line for file selection:
<input id="attached_file" name="attached_file" style="width:220px;" placeholder="Enter an amount - No $ sign" type="file" value="" onfocus="jQuery(this).prev("input").attr("checked", true); if(jQuery(this).val() == "Other") { jQuery(this).val(""); }" onblur="if(jQuery(this).val().replace(" ", "") == "") { jQuery(this).val("Other"); }" tabindex="18">
How can I get the actual file data to pass as well?
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 submission.
The issue I am having is getting the file to pass thru ajax correct. I can't quite mesh it together properly to get the results that I am looking for which is the file posting to my php script. Here's my code for passing the data:
$(document).ready(function() {
$("#submit_btn").click(function() {
var proceed = true;
//simple validation at client's end
//loop through each field and we simply change border color to red for invalid fields
$("#contact_form input[required=true], #contact_form textarea[required=true]").each(function(){
$(this).css('border-color','');
if(!$.trim($(this).val())){ //if this field is empty
$(this).css('border-color','red'); //change border color to red
proceed = false; //set do not proceed flag
}
//check invalid email
var email_reg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
if($(this).attr("type")=="email" && !email_reg.test($.trim($(this).val()))){
$(this).css('border-color','red'); //change border color to red
proceed = false; //set do not proceed flag
}
});
if(proceed) //everything looks good! proceed...
{
//get input field values data to be sent to server
var search_array = $('input[name="donation"]').map(function(){
return $(this).val();
}).get();
post_data = {
'user_name' : $('input[name=full_name]').val(),
'user_email' : $('input[name=email]').val(),
'address' : $('input[name=address]').val(),
'address2' : $('input[name=address2]').val(),
'city' : $('input[name=city]').val(),
'state' : $('input[name=state]').val(),
'zip' : $('input[name=zip]').val(),
'ccnum' : $('input[name=ccnum]').val(),
'expmonth' : $('select[name=expmonth]').val(),
'expyear' : $('select[name=expyear]').val(),
'cardname' : $('input[name=cardname]').val(),
'ccvcode' : $('input[name=ccvcode]').val(),
'donation' : $('input[name=donation]:checked').val(),
'donation_other' : $('input[name=donation_other]').val(),
'contact_phone' : $('input[name=contact_phone]').val(),
'attached_file' : $('input[name=attached_file]').val(),
'donatecomments' : $('textarea[name=donatecomments]').val()
};
//Ajax post data to server
$.post('https://www.xxxxxx.org/catch.php', post_data, function(response){
if(response.type == 'error'){ //load json data from server and output message
output = '<div class="error">'+response.text+'</div>';
}else{
output = '<div class="success">'+response.text+'</div>';
//reset values in all input fields
$("#contact_form input[required=true], #contact_form textarea[required=true]").val('');
$("#contact_form #contact_body").slideUp(); //hide form after success
window.top.location.href = "https://www.xxxxxxxxx.org/thank-you";
}
$("#contact_form #contact_results").hide().html(output).slideDown();
}, 'json');
}
});
//reset previously set border colors and hide all message on .keyup()
$("#contact_form input[required=true], #contact_form textarea[required=true]").keyup(function() {
$(this).css('border-color','');
$("#result").slideUp();
});
});
And my line for file selection:
<input id="attached_file" name="attached_file" style="width:220px;" placeholder="Enter an amount - No $ sign" type="file" value="" onfocus="jQuery(this).prev("input").attr("checked", true); if(jQuery(this).val() == "Other") { jQuery(this).val(""); }" onblur="if(jQuery(this).val().replace(" ", "") == "") { jQuery(this).val("Other"); }" tabindex="18">
How can I get the actual file data to pass as well?
Share Improve this question edited Jan 10, 2018 at 11:19 halfer 20.4k19 gold badges108 silver badges201 bronze badges asked Jun 15, 2016 at 4:04 MrTechieMrTechie 1,8476 gold badges21 silver badges36 bronze badges 2- You need to pass it as FormData. I will do an example. – mwilson Commented Jun 15, 2016 at 4:09
- @mwilson - Thanks! I can't quite figure it out properly. Other examples take a different route than what this is. – MrTechie Commented Jun 15, 2016 at 4:12
4 Answers
Reset to default 9You'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)
{
}
}
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);
}
}
});
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>
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
});