Form submission oncomplete - javascript

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?

Related

Chrome extension : simulate key press in current tab

With the best of my abilities (absolutely not a dev), I'm trying to developp a Chrome extension that resume a Netflix session on another computer.
When I click the extension, the current URL of the tab is sent to another computer and there the URL is captured and a Netflix is started.
And it works!
1) But I'd like the current TAB to be paused, so simulate the sending of the SPACE key.
Please do you know how I can do that?
2) Also, when I click on the plugin, I then have to click on the "Save bookmark" button to actually send the link.
Please is there a way to just send the link when I'm actually clicking on the plugin : basically the link is sent without having to click on "Save bookmark"?
I know these are super noob questions, I tried to find myself, but I'm really really bad at this!
Thank you in advance!
popup.js
// This callback function is called when the content script has been
// injected and returned its results
function onPageDetailsReceived(pageDetails) {
document.getElementById('title').value = pageDetails.title;
document.getElementById('url').value = pageDetails.url;
document.getElementById('summary').innerText = pageDetails.summary;
}
// Global reference to the status display SPAN
var statusDisplay = null;
// POST the data to the server using XMLHttpRequest
function addBookmark() {
// Cancel the form submit
event.preventDefault();
// The URL to POST our data to
var postUrl = 'http://192.168.0.16/netflix/index.php';
// Set up an asynchronous AJAX POST request
var xhr = new XMLHttpRequest();
xhr.open('POST', postUrl, true);
// Prepare the data to be POSTed by URLEncoding each field's contents
var title = encodeURIComponent(document.getElementById('title').value);
var url = encodeURIComponent(document.getElementById('url').value);
var summary = encodeURIComponent(document.getElementById('summary').value);
var tags = encodeURIComponent(document.getElementById('tags').value);
var params = 'title=' + title +
'&url=' + url +
'&summary=' + summary +
'&tags=' + tags;
// Replace any instances of the URLEncoded space char with +
params = params.replace(/%20/g, '+');
// Set correct header for form data
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
// Handle request state change events
xhr.onreadystatechange = function() {
// If the request completed
if (xhr.readyState == 4) {
statusDisplay.innerHTML = '';
if (xhr.status == 200) {
// If it was a success, close the popup after a short delay
statusDisplay.innerHTML = 'Saved!';
window.setTimeout(window.close, 1000);
} else {
// Show what went wrong
statusDisplay.innerHTML = 'Error saving: ' + xhr.statusText;
}
}
};
// Send the request and set status
xhr.send(params);
statusDisplay.innerHTML = 'Saving...';
}
// When the popup HTML has loaded
window.addEventListener('load', function(evt) {
// Cache a reference to the status display SPAN
statusDisplay = document.getElementById('status-display');
// Handle the bookmark form submit event with our addBookmark function
document.getElementById('addbookmark').addEventListener('submit', addBookmark);
// Get the event page
chrome.runtime.getBackgroundPage(function(eventPage) {
// Call the getPageInfo function in the event page, passing in
// our onPageDetailsReceived function as the callback. This injects
// content.js into the current tab's HTML
eventPage.getPageDetails(onPageDetailsReceived);
});
});
event.js
// This function is called onload in the popup code
function getPageDetails(callback) {
// Inject the content script into the current page
chrome.tabs.executeScript(null, { file: 'content.js' });
// Perform the callback when a message is received from the content script
chrome.runtime.onMessage.addListener(function(message) {
// Call the callback function
callback(message);
});
};
popup.html
<body>
<form id="addbookmark">
<p><label for="title">Title</label><br />
<input type="text" id="title" name="title" size="50" value="" /></p>
<p><label for="url">Url</label><br />
<input type="text" id="url" name="url" size="50" value="" /></p>
<p><label for="summary">Summary</label><br />
<textarea id="summary" name="summary" rows="6" cols="35"></textarea></p>
<p><label for="tags">Tags</label><br />
<input type="text" id="tags" name="tags" size="50" value="" /></p>
<p>
<input id="save" type="submit" value="Save Bookmark" />
<span id="status-display"></span>
</p>
</form>
</body>

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.

Adding a file option to the present form field

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!

Upload files Using Ajax, Jquery and Struts2

Hi can any one please tell me how to upload files using ajax, jquery and Struts2. I have gone through the lot of tutorials in the net but i didn't get any possible solution. The requirement is when ever we click on the button the javascript function need to be called.The javascript(jquery) initiate the Ajax engine and ajax need to call the struts action to get the response. Here the request and response is without refresh the page and without using the IFrames.
I use iframe to submit my data without refresh.
i) My html is as follows :
1) Add form tag. // You can just copy paste my form tag just change the action
2) Add target="my_iframe" // The iframe name.. it can be anything
<div class="bp_up_input">
<form name="banner_image_uploads" id="banner_image_uploads" method="post" action="" target="my_iframe" enctype="multipart/form-data">
<span>
<input type="file" name="banner_image" class="my_vld" lang="Image_path" />
<input type="button" id="banner_image_upload" value="Upload" class="bp_button_style" />
</span>
<input type="hidden" name="slt_store_id" value="" />
<input type="hidden" name="sld_location" value="" />
</form>
</div>
ii) My javascript code is a follows :
$('#banner_image_upload').live('click',function(){
if($.trim($('input[name="banner_image"]').val()) != '' && $.trim($('select[name="bp_location"]').val()) != '' && $.trim($('#store_names').val()) != ''){
$("iframe").remove(); //Remove previous iframe if present
$("body").append('<iframe id="my_iframe" name="my_iframe" src="" style="display:none;"></iframe>'); //Append iframe to body with id my_iframe
$('#banner_image_uploads').submit();//submit the form with id banner_image_uploads
$("#my_iframe").load(function(){
var val = $("iframe")[0].contentDocument.body.innerHTML; // I use php so I just echo the response which I want to send e.g 250:new and save it in var val.
var data = val.split(':'); // I split the variable by :
var html = '<tr><td><img width="800" height="60" border="0" src="/assets/store_banners/live/'+$.trim($('input[name="sld_location"]').val())+'/'+data[1]+'" id="'+data[0]+'"><img src="/images/delete_trash.png" width="9" height="12" class="image_delete" style="padding-left:37%;"/></td></tr>'; // In my case I wanted to upload an image so on success I had to show the image which was uploaded. You can skip this and the below code if you want.
$('.bp_table tbody').append(html); //Append the uploaded image to the container I wanted.
$('input[name="banner_image"]').val(''); //On success I clear the file name
});
}else{
alert('Please Select filters');
}
Hi the below code is working for me. I hope it will help you.
JSP Code:
<div id="uploadImg">
<s:form id="uploadImgForm" action="strutsaction" method="post" enctype="multipart/form-data">
<s:file name="imgFileUpload" label="Choose file to upload" accept="image/*"></s:file>
<s:submit value="Upload" align="center" id="uploadImgSubmitBtn"></s:submit>
</s:form>
<div>
JQuery:
$("#uploadImgSubmitBtn").click(function(e){
// Get form
var form = $('#uploadImgForm')[0];
// Create an FormData object
var data = new FormData(form);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "strutsaction.action",
data : data,
cache: false,
processData: false,
contentType: false,
success: function(data){
$('#uploadImg').html(data);
}
});
});

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