Adding a file option to the present form field - javascript

I have a feedback form in my website. Its very basic and only having a text area to put user feedback and submit.
now i am planing to add one option for attaching a picture along with feedback. Adding another text field easy but
i can't figure out how can i add a file into the JavaScript. Please suggest the required changes to add a file into the below script
function upload() {
var feedback = _("feedback").value;
var status = _("status");
if (feedback == "") {
status.innerHTML = "Empty";
} else {
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "feedback.php");
ajax.onreadystatechange = function() {
if (ajaxReturn(ajax) == true) {
if (ajax.responseText != "ok") {
status.innerHTML = ajax.responseText;
} else {
window.location = "thanks.php";
}
}
}
ajax.send("feedback=" + feedback);
}
}
<form id="form1" enctype="multipart/form-data" onsubmit="return false;">
<input id="feedback" type="text">
<button id="submit" onclick="upload()">Submit Details</button>
<span id="status"></span>
</form>

Here you are:
var x = document.createElement("input");
x.setAttribute("type", "file");
document.querySelector("#form1").appendChild(x);
Hope this help.

Unless you're trying to upload the file using ajax, just submit the form to feedback.php.
<form enctype="multipart/form-data" action="feedback.php" method="post">
<input id="image-file" type="file" />
</form>
If you want to upload the image in the background (e.g. without submitting the whole form) you'll need to use Flash since JavaScript alone can't do this.
jQuery Ajax File Upload
Ajax using file upload
jquery easy example look at first answer

Okay.. so two things you will have t change:
Remove that header ('application/x-www-form-urlencoded') and add 'multipart/form-data' header instead. files can not be sent as urlencoded.
Secondly, in ajax request, instead of sending feedback as string, you need to send FormData object, which supports file upload over ajax:
var myForm = $("#form1")[0];
var formData = new FormData(myForm);
ajax.send(formData);
Update:
Forgot to mention: Of course the third thing you will need is to add to your form!

Related

JS Change function working only first time

In this, I have a give module (wordpress plugin for fundraiser) and I have integrated the file upload
https://www.mamafrica.it/26964-2/
I have add a java script in order to check the file size and file type, but this work only until I not change the payment method.
For example:
After load page, if I load file > 500KB or different from pdf or jpg, error message appears under the file upload area.
If I switch to "Donation by bank transfer" the form change (an information text appears before file upload area and the form fields are cleaning).
Now, if I choose another file > 500KB (or not pdf or jpg) the error message not appears.
The 'change', function in javascript is not invoked.
This is the javascript
<script>
var inputElement = document.getElementById("fileToUpload")
inputElement.addEventListener('change', function(){
alert("QUI");
var error = 0;
var fileLimit = 500; // In kb
var files = inputElement.files;
var fileSize = files[0].size;
var fileSizeInKB = (fileSize/1024); // this would be in kilobytes defaults to bytes
var fileName = inputElement.value;
idxDot = fileName.lastIndexOf(".") + 1;
extFile = fileName.substr(idxDot, fileName.length).toLowerCase();
document.getElementById("error").innerHTML = "";
document.getElementById("filenamecheck").innerHTML = inputElement.value;
if (extFile=="jpg" || extFile=="pdf"){
console.log("Type ok");
} else {
error = 1;
document.getElementById("error").innerHTML = "Solo file .pdf o .jpg";
document.getElementById("fileToUpload").value = "";
}
if (error == 0) {
if(fileSizeInKB < fileLimit) {
console.log("Size ok");
} else {
console.log("Size not ok");
document.getElementById("error").innerHTML = "Massima grandezza file: " + fileLimit + "KB";
document.getElementById("fileToUpload").value = "";
}
}
})
</script>
This the file upload area
<div class="file-uploader">
<input id="fileToUpload" name="fileToUpload" type="file" accept=".pdf,.jpg"/>
<label for="file-upload" class="custom-file-upload">
<i class="fas fa-cloud-upload-alt"></i>Clicca per scegliere il file
<span name="filenamecheck" id="filenamecheck">test</span>
</label>
<p id="error" style="color: #c00000"></p>
</div>
Someone can help me?
UPDATE: The correct URL is https://www.mamafrica.it/26964-2/
UPDATE SOLVE
I have found a solution for my problem!!
First time, I have insert the javascript code after the end of form tag and the refresh work only on elements inside of form tag.
Using a wordpress hook (in function.php) i have insert the javascrip code immediatly after the input tag, inside of the form tag, in this way, the form refresh, reload also the javascript.
Thank you all!
Regards,
Marco
UPDATE
I have found a solution for my problem!!
First time, I have insert the javascript code after the end of form tag and the refresh work only on elements inside of form tag. Using a wordpress hook (in function.php) i have insert the javascrip code immediatly after the input tag, inside of the form tag, in this way, the form refresh, reload also the javascript.
Thank you all!
Could be that you are using:
inputElement.addEventListener
That might be only triggered once.
You might use something in a form as simple as:
onSubmit="return MyFunctionName"
That is being used in form validation for years.
I hope this helps,
Ramon

Node js - Redirect to url with post data like form

I am new to NodeJS . I want to send data to page with redirect multiple parameters like html form as below :
<form action="https://example.com/payment.aspx" method="post">
<input type="hidden" name="Amount" value="5000"/>
<input type="hidden" name="ResNum" value="sdsadasd231323"/>
<input type="submit" id="startBankPayment" class="btn btn-lg btn-success col-md-5" value="startPayment"/>
</form>
I need a sample code send data to url and redirect to this url like form submit button clicked ?
function submitForm(){
var a = document.getElementById('Amount').value;
var b = document.getElementById('ResNum').value;
var holder = {Amount : a, ResNum : b};
var xhr1 = new XMLHttpRequest();
xhr1.open('POST', "https://example.com/payment.aspx", true);
xhr1.onreadystatechange = function() {
if (this.status == 200 && this.readyState == 4) {
//ADD CODE to redirect my page when I get my data back
}//
};//end onreadystate
xhr1.send(JSON.stringify(holder));//the object you are sending
}
Here is a sample that should help. You execute this function when your button is clicked, so you need to add the click="submitForm()" to your button. You also need to add id="Amount" and id="ResNum" to those fields. You also wouldn't need the form action anymore since this takes care of the actual post. You also need to know how the form is being read on the server end and what type of encoding you need. You may be able to send as form encoded data or you may need to JSON.stringify() the object before you send it off incase it is parsed as jsonencoded data, which I included.

How do I post data to the server without leaving the current page?

What I want is having a JavaScript function which sends a POST to an arbitrary site and stays the whole time on the site 'it was executed on'. It does not necessarily have to be done with a form!
I don't want to use jQuery, if possible.
How can I do this?
You can "prevent" the default behavior.
<form id="myform">
Name: <input id="name" type="text" value="onur" /><br />
Email: <input id="email" type="text" value="onur#email.com" /><br />
<br />
<button type="submit">type=submit</button>
<button type="button" onclick="form.submit()">form.submit()</button>
</form>
Before the </body> tag (or on DOM ready);
var form = document.getElementById('myform');
function onSubmit(event) {
if (event) { event.preventDefault(); }
console.log('submitting');
postFormData(form); // <-------- see below
}
// prevent when a submit button is clicked
form.addEventListener('submit', onSubmit, false);
// prevent submit() calls by overwriting the method
form.submit = onSubmit;
Fiddle here
EDIT:
The default behavior of form.submit() will redirect the page to the form.action URL. This is an approach on how you simulate the default behavior without redirecting to another page.
And since you want to "POST" the form, here is the method (AJAX stuff):
function postFormData(form) {
var xhr = new XMLHttpRequest(),
formData = urlEncodeFormData(form); // see below
// set XHR headers
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
// watch for state changes
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
// This is where you show a success message to the user
}
};
// open and send the post request
xhr.open('POST', 'https://myweb.com/action-target', true);
xhr.send(formData);
}
// You could use the FormData API if the browser supports it.
// Below is somewhat alternate and should be improved to support more form element types.
function urlEncodeFormData(form) {
var i, e, data = [];
for (i = 0; i < form.elements.length; i++) {
e = form.elements[i];
if (e.type !== 'button' && e.type !== 'submit') {
data.push(encodeURIComponent(e.id) + '=' + encodeURIComponent(e.value));
}
}
return data.join('&');
}
See:
MDN — Using XMLHttpRequest
MDN — FormData
Can I Use FormData?
Give your form an onsubmit handler that returns false. Do whatever processing you need to do in there (eg: ajax send data or what have you)
Code's untested, but here's the general idea.
function doFormThings() {
//processing form here
return false; //don't actually redirect, browser, I'm watching you
};
<form onsubmit="return doFormThings();">
Since you are dynamically creating the form, you can create it in an iframe and submit it inside of the iframe - that way you won't leave the current page and you'll actually use normal form submit. Here is a working example:
function generateFormAndSubmit()
{
// Create an input for the form
var input = document.createElement( 'input' );
input.type = 'hidden';
input.name = 'test'
input.value = '123';
// Create the form itself
var form = document.createElement( 'form' );
form.action = '/myaction';
// Append the created input to the form
form.appendChild( input );
// Create the iframe that will hold the form
var iframe = document.createElement( 'iframe' );
// Make it offscreen, so it's not visible for the user
iframe.style.cssText = 'width: 1px;height: 1px;position: absolute;top: -10px;left: -10px';
// Append the iframe to our document
document.body.appendChild( iframe );
// Append the form to the iframe
iframe.contentDocument.body.appendChild( form );
// Submit the form
form.submit();
}
You can call the submit of the form from another place, of course, like a button for an example - the iframe is yours, so you can manipulate (search for the form, modify it, submit it, etc.) it's contents at any point - no security restrictions will apply.
If you need a result of the submit, then it's a bit more complicated - first, the action of the form needs to point to the same domain. Then, if that is true, you just listen for when the iframe is loaded and read the result from it's content (either printed in the document JS or parse the DOM in some way).
You can simply have an iframe and change the form's target to post the data into it. E.g:
<form method='POST' target='hd-submit'>
<input name='firstName' placeholder='First Name' type='text' />
<input name='lastName' placeholder='Last Name' type='text' />
<input type='submit' value='Send' />
</form>
<iframe name='hd-submit' hidden></iframe>

Form submission oncomplete

So on my page, I have a button where user can export the data to EXCEL/PDF. The way it works is they click on the button and then I send the data into a hidden form which submits the request. Once the request is done, it returns the content of the document type that the user selected which prompts the "Save As" dialog.
<form id="export-form" action="laravel-excel.php" method="POST" target="hidden-form">
<input type="hidden" name="type" value="{{header.export.type}}" />
<input type="hidden" name="name" value="{{header.export.name}}" />
<input type="hidden" name="data" value="{{header.export.data}}" />
</form>
<iframe style="display:none" name="hidden-form"></iframe>
So everything works as it should! However, I want to add a loader to let people know that the file is processing and when its done, I want to hide it. Well based on my research I was unable to find a solution that works for forms. The solutions I found are ones where the processing happens via AJAX like so:
$('#export-form').ajaxForm({
success: function (response, status, request)
{
var disp = request.getResponseHeader('Content-Disposition');
if (disp && disp.search('attachment') != -1)
{
var type = request.getResponseHeader('Content-Type');
var blob = new Blob([response], { type: type });
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
window.location = downloadUrl;
}
}});
Is there a better solution out there?

Handling Json results in ASP.NET MVC with jQuery

I am working on a view containing two forms, handled by separate controller actions which return a string serilaized to Json:
return Json(message);
The forms are submitted using jQuery, by clicking on a button outside the two forms.
The button handler:
$('#inviteForm').ajaxSubmit({
success: function(html, status) {
$("#response").text(html);
}
})
$('#trialForm').ajaxSubmit({
success: function(html, status) {
$("#response").append(html);
}
});
The browser receives the result and prompts the user to download as it is interpreted as "application/json".
However, if I only submit one of these forms in the jQuery, the resulting Json message is displayed as a string in the #response element as desired.
Why does adding a second ajaxSubmit() cause this different behaviour?
Thanks.
The view contains the following forms:
<form action="/Controller1/SaveAttachments/<%=Model.ObjectId %>" id="trialForm" method="post" enctype="multipart/form-data">
<input type="file" name="trialForm" size=30/>
<input type="file" name="trialSheet" size=30/>
<input type="file" name="trialApproval" size=30/>
</form>
and...
<form action="/Controller1/UpdateTemplate/<%=Model.ObjectId %>" id="inviteForm" method="post" enctype="multipart/form-data">
<%=Html.TextArea("invitationSheet", Model.InvitationSheet,
new { #name = "invitationSheet"})
<script type="text/javascript">
window.onload = function() {
var sBasePath = '<%=Url.Content("~/Content/FCKeditor/")%>';
var oFCKeditor = new FCKeditor('invitationSheet');
oFCKeditor.BasePath = sBasePath;
oFCKeditor.HtmlEncodeOutput = true;
oFCKeditor.ReplaceTextarea();
}
</script>
</form>
Update:
You can't upload files directly via AJAX so it is doing an actual post of the form containing file inputs. You should look at a plugin that will let you upload files using the hidden iframe technique that works asynchronously instead of trying to upload using AJAX.

Categories

Resources