I am not a javascript coder, but was trying to figure out a solution with using HTML Web Forms and Javascript... However, I am using a while loop to keep checking the status of a submitted job, but because I am doing this, the page freezes. Is there way to check the status without having the page freeze?
<!DOCTYPE html>
<html>
<body>
<p><span style="background-color:{color}; border-radius:3px; color:#ffffff; float:right; font-size:16px; padding:2px 4px 2px 4px"><a id='downLoad' href="" download='file' style='display:none' target='_blank'>Save file As</a></span><span style="font-size:24px"><span style="color:#d52b40">Print Survey Report </span></span></p>
<p>Enter the project <b>Print ID</b> and <b>File Name</b> then submit the report for print. Repot may take a few minutes, but a <b>Save File As link</b> will show when ready for download. Right click and select <b>Save Link As</b></p>
<form id='printSurvey'>
<input type="hidden" id="portalUrl" name="portalUrl" value="https://transportation.bd.esri.com/portal">
<input type="hidden" id="templateItemId" name="templateItemId" value="a19dc0354ade4e9da65086453d89aa4a">
<input type="hidden" id="surveyItemId" name="surveyItemId" value="901946f3a7f940f4bab7bbda9d7595e3">
<input type="hidden" id="featureLayerUrl" name="featureLayerUrl" value="https://transportation-rh.bd.esri.com/server/rest/services/Geotech/GeotechProjectInfoPointSDE/FeatureServer/2">
<input type="hidden" id="token" name="token" value="toekn was removed">
<input type="hidden" id="outputFormat" name="outputFormat" value="docx">
<input type="hidden" id="uploadInfo" name="uploadInfo[type]" value="arcgis">
<input type="hidden" id="uploadInfo" name="uploadInfo[parameters][folderId]" value="6128cd36706f40ddaaa387e9296032a9">
<input type="hidden" id="uploadInfo" name="uploadInfo[parameters][conflictBehavior]" value="rename">
<label for="queryParameters">Print ID:</label>
<input type="text" id="queryParameters" name="queryParameters[objectIds]" placeholder="i.e 1"><br><br>
<label for="outputReportName">Report Name:</label>
<input type="text" id="outputReportName" name="outputReportName" placeholder="Logging Report Name"><br><br>
<input type="hidden" id="outputPackageName" name="outputPackageName" >
<input type="submit" type="buton" value="Submit">
</form>
<script>
document.getElementById("outputReportName").addEventListener('focusout',function () {
document.getElementById("outputPackageName").value = this.value;
});
const downLoadTag = document.getElementById('downLoad');
function httpGet(url){
let xmlHttpReq = new XMLHttpRequest();
var url = url +'?portalUrl=https://transportation.bd.esri.com/portal&token=token was removedenter code here'
xmlHttpReq.open("GET", url, false);
xmlHttpReq.send(null);
return JSON.parse(xmlHttpReq.responseText);
}
window.addEventListener("load", () => {
function sendData() {
const XHR = new XMLHttpRequest();
// Bind the FormData object and the form element
const FD = new FormData(form);
// Define what happens on successful data submission
setTimeout(XHR.addEventListener("load", (event) => {
//alert(event.target.responseText['jobId']);
var responseArray = JSON.parse(event.target.responseText);
var jobID = responseArray['jobId'];
var urlPath = 'https://survey123.arcgis.com/api/featureReport/jobs/'+jobID
var status = 'esriJobExecuting'
alert('Report is being generated... This may take several minutes');
var countEnd = 0
while (status != 'esriJobSucceeded') {
var getRep = httpGet(urlPath)
if (getRep['jobStatus'] == 'esriJobSucceeded'){
var itemID = getRep['resultInfo']['resultFiles'][0]['id'];
var urlBeg = 'https://transportation.bd.esri.com/portal/sharing/rest/content/items/';
var urlEnd = '/data?token=token was removed';
downLoadTag.href = urlBeg +itemID+urlEnd;
//console.log(getRep['resultInfo']);
status = getRep['jobStatus'];
//console.log(getRep);
alert('Report is ready for download')
};
};
downLoadTag.style='display:show';
}), 5);
// Define what happens in case of error
XHR.addEventListener("error", (event) => {
alert('Oops! Something went wrong.');
});
// Set up our request
XHR.open("POST", 'https://survey123.arcgis.com/api/featureReport/createReport/submitJob');
// The data sent is what the user provided in the form
XHR.send(FD);
};
// Get the form element
const form = document.getElementById("printSurvey");
// Add 'submit' event handler
form.addEventListener("submit", (event) => {
event.preventDefault();
sendData();
});
});
</script>
</body>
</html>
I struggled with the same problem recently. There is a Web Workers API. It does everything in the background and doesn't block the main thread. It is easy to learn and understand. Just google Web Workers API and you will get it!
Related
So basically i am trying to implement 2checkout in my website and i have done everything from documentation but i get this error: TwoCheckoutException: Bad request - parameter error. I tried checking and playing with private/public keys and id but when i change them it says "authoization error" so i am sure they are okay. I read about addresses and everything and i have changed them but still not working.
Here is my full code:
#{
ViewData["Title"] = "Test";
}
<script type="text/javascript" src="https://www.2checkout.com/checkout/api/2co.min.js"></script>
<h2>Test</h2>
<form id="myCCForm" action="/Home/SubmitCard" method="post">
<input name="token" type="hidden" value="" />
<div>
<label>
<span>Card Number</span>
<input id="ccNo" type="text" value="" autocomplete="off" required />
</label>
</div>
<div>
<label>
<span>Expiration Date (MM/YYYY)</span>
<input id="expMonth" type="text" size="2" required />
</label>
<span> / </span>
<input id="expYear" type="text" size="4" required />
</div>
<div>
<label>
<span>CVC</span>
<input id="cvv" type="text" value="" autocomplete="off" required />
</label>
</div>
<input type="submit" value="Submit Payment" />
</form>
<script type="text/javascript">
// Called when token created successfully.
var successCallback = function (data) {
var myForm = document.getElementById('myCCForm');
// Set the token as the value for the token input
myForm.token.value = data.response.token.token;
// IMPORTANT: Here we call `submit()` on the form element directly instead of using jQuery to prevent and infinite token request loop.
myForm.submit();
};
// Called when token creation fails.
var errorCallback = function (data) {
if (data.errorCode === 200) {
alert("Error 200");
// This error code indicates that the ajax call failed. We recommend that you retry the token request.
} else {
alert(data.errorMsg);
}
};
var tokenRequest = function () {
// Setup token request arguments
var args = {
sellerId: "901417674",
publishableKey: "309FC596-8380-4B6F-B269-3E157A5A5D0B",
ccNo: $("#ccNo").val(),
cvv: $("#cvv").val(),
expMonth: $("#expMonth").val(),
expYear: $("#expYear").val()
};
// Make the token request
TCO.requestToken(successCallback, errorCallback, args);
};
$(function () {
// Pull in the public encryption key for our environment
TCO.loadPubKey('sandbox');
$("#myCCForm").submit(function (e) {
// Call our token request function
tokenRequest();
// Prevent form from submitting
return false;
});
});
</script>
and here is server side code:
public IActionResult SubmitCard()
{
TwoCheckout.TwoCheckoutConfig.SellerID = "901417674";
TwoCheckout.TwoCheckoutConfig.PrivateKey = "4E704021-B233-435F-A904-47B2620B9E66";
TwoCheckout.TwoCheckoutConfig.Sandbox = true;
try
{
TwoCheckout.AuthBillingAddress Billing = new TwoCheckout.AuthBillingAddress();
Billing.addrLine1 = "123 Main Street";
Billing.city = "Townsville";
Billing.zipCode = "43206";
Billing.state = "Ohio ";
Billing.country = "USA";
Billing.name = "Joe Flagster";
Billing.email = "Ex#a.com";
Billing.phoneNumber = "065";
TwoCheckout.ChargeAuthorizeServiceOptions Customer = new TwoCheckout.ChargeAuthorizeServiceOptions();
Customer.total = 1;
Customer.currency = "USD";
Customer.merchantOrderId = "12";
Customer.billingAddr = Billing;
Customer.token = Request.Form["token"];
TwoCheckout.ChargeService Charge = new TwoCheckout.ChargeService();
var result = Charge.Authorize(Customer);
return View("Success", result);
}
catch(TwoCheckout.TwoCheckoutException ex)
{
return View("Error", ex.ToString());
}
}
and here is all info from my sandbox:
You may need to update your site settings for sandbox from Site Management -> Site Settings and Turn to On for Demo Settings and check again
May it helps you
I am currently working on an website project that my friends and I would like to publish in the future. I´m currently building the html and css side of the page and need to implement dynamic events (if that's how its called) in the page for customer input.
I have a very little understanding when it comes to javascript/jquery (I am able to get a general idea of what is happening, yet my syntax comprehension is poop) and have only a basic knowledge of html and css. Now, I am aware that my inquiry is extensive and I would really appreciate any help, or pointers in the right direction!
So far the different blocks of code that I have found and tried by googling have worked for me, but only in executing individual functions (e.g.: the toggle function works but the create.element function doesn't).
This is my current html code that I am trying to modify with Javascript:
<div class="bttiendas">
<button class="btndag">Agregar</button>
<button class="btndgu">Guardar</button>
</div>
<div class="rdatos">
<form class="thf">
<input class="morehf" type="button" value="+/-" />
<input class="chf" type="text" placeholder="Lorem ipsum" readonly />
<input class="chf" type="text" placeholder="Lorem ipsum" readonly />
<input class="chf" type="text" placeholder="Lorem ipsum" readonly />
<input class="edithf" type="button" value="Edit" />
<input class="erasehf" type="reset" value="Erase" />
</form>
<form class="trf">
<input class="crf" type="text" placeholder="POS" readonly />
<input class="crf" type="text" disabled />
<input class="crf" type="text" disabled />
<input class="crf" type="text" disabled />
</form>
</div>
What I am trying to accomplish with Javascript is as follows:
-To be able to create with javascript both .thf and .trf forms dynamically along with every other input/button that is inside each form with clicking the .btndag button (this is an onclick event followed by create.element if I'm not mistaken).
-For the .morehf <input button> have a hide/show toggle function for .trf and anything else inside that form.
-Toggle disabled in the .crf input text boxes with the .edithf <input button>.
-To be able to erase/remove both .thf and .trf forms (their input textboxes AND the buttons .morehf .edithf .erasehf) with the .erasehf <input button>.
-And to be able to save/submit (I am not sure which is the correct term here) any added and completely filled out forms fields (for when we want to send the changes to our database).
Again I would greatly appreciate any help you could give me, and thank you in advance for your time.
You can import jquery into your solution.
For step 1: you do not make sense. Do you mean you want to load data into your form from somewhere to edit data or something? how is this dynamic? It looks like static forms on a page.
For step 2:
<input class="morehf" onclick="toggleTrf()" type="button" value="+/-" />
<script>
function toggleTrf() {
$(".trf").toggle()
}
</script>
step 3:
<input class="edithf" onclick="disableInputs()" type="button" value="Edit" />
<script>
function disableInputs() {
if($(".crf").is(":disabled");){
//jquery 1.6+
$(".crf").prop('disabled', false);
//jquery 1.5 -
$(".crf").removeAttr('disabled');
}
else {
//jquery 1.6+
$(".crf").prop('disabled', true);
//jquery 1.5 -
$(".crf").attr('disabled','disabled');
}
}
</script>
step 4: it is not clear what you mean by erase the form but you can clear the text in the inputs
<input class="erasehf" thpe="reset" onclick="clearInputs()" value="Erase" />
<script>
function clearInputs() {
$("input").val("")
}
</script>
step 5:
<form action="some/path">
<input name="someName" type="text" text="random field" value="1" />
<button type="submit">submit</button>
</form>
That submit button will submit the form to whatever path you specify in your form action. As for saving to the database etc it is impossible to guess what technology you will use to do that.sorry about code formattin im typing on a phone.
I believe I have included everything the OP wanted. The non-jQuery approach (ES6). JSFiddle
First lets add a few helper variables:
let formSets = 0;
let createForm = function(id) {
return `<form data-id='${id}' class="thf">
<input class="morehf" type="button" value="+/-" />
<input class="chf" type="text" placeholder="Lorem ipsum" readonly />
<input class="chf" type="text" placeholder="Lorem ipsum" readonly />
<input class="chf" type="text" placeholder="Lorem ipsum" readonly />
<input class="edithf" type="button" value="Edit" />
<input class="erasehf" type="reset" value="Erase" />
</form>
<form data-id='${id}' class="trf">
<input class="crf" type="text" placeholder="POS" readonly />
<input class="crf" type="text" disabled />
<input class="crf" type="text" disabled />
<input class="crf" type="text" disabled />
</form>`;
};
Add the onclick event for the "add" function. We have to reassign the click events to the dynamically added elements or we could have done event delegation like I did for the remove button:
document.getElementsByClassName('btndag')[0].onclick = () => {
document.getElementById('a').innerHTML += createForm(++formSets);
for (let ii = 0; ii < formSets; ii++) {
document.getElementsByClassName("morehf")[ii].onclick = () => {
document.getElementsByClassName("trf")[ii].classList.toggle('hide');
}
document.getElementsByClassName("edithf")[ii].onclick = () => {
let form = document.getElementsByClassName("trf")[ii].children;
for (let i = 0; i < form.length; i++) {
let input = form[i];
if (input.disabled == true) {
input.disabled = false;
} else {
input.disabled = true;
}
}
}
}
};
Add the remove button a little differently using event delegation which allows us to target another element based on the parents target:
document.getElementById('a').onclick = function(e) {
let t = e.target;
if (t.className == 'erasehf') {
let me = t.parentNode;
let sib = me.nextElementSibling;
me.parentNode.removeChild(me);
sib.parentNode.removeChild(sib);
}
}
Finally, submit the data. This part is a little more vague simply because I am not exactly sure how you want the data formatted. But here is how you would submit the form using AJAX:
document.getElementsByClassName('btndgu')[0].onclick = function() {
Request("/linkto/save.asp").post({
//datahere
}).then(function () {
//on success
}, function () {
//on failure
});
}
Note that this uses a helper AJAX function that I made:
let Request = function(url, opt) {
// start loader
var AJAX = function(type, url, data, success, failure, cache) {
var InitRequest = new Promise(function(accept, reject) {
var request = new XMLHttpRequest(); // initiate new XMLHttpRequest
var done = false;
var compile = function(data) { //turn the data object into a usable source for the send function
var send = [];
for (var item in data) { // compile all data in "item=data" strings
send.push(item + "=" + encodeURIComponent(data[item]));
}
send = send.join("&"); // combine data to form "item1=data1&item2=dat2&item3=data3"
return send;
};
// if we choose not send any data, then the data variable will take the place of the success variable
// because of this, we have to also shift the failure function
if (typeof data === "function") {
success = data || accept;
failure = success || reject;
data = "";
} else {
success = success || accept;
failure = failure || reject;
data = compile(data);
}
if (type.toUpperCase() == 'POST') {
request.open(type.toUpperCase(), url, true);
// this header allows POST requests to work
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
} else if (type.toUpperCase() == 'GET') {
// for GET requests, we need to put all data in the url
// we would end up with test.php?item1=data1&item2=dat2&item3=data3
request.open(type.toUpperCase(), url + "?" + data, true);
} else {
console.error('Incorrect request type submitted: "' + type + '" is not supported.');
return false;
}
// in order for laravel to properly send ajax requests
request.setRequestHeader('X-CSRF-TOKEN', $('meta[name="csrf-token"]').attr('content'));
request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
request.onreadystatechange = function() {
if (!done) {
if (request.readyState === 4) { // when the readyState == 4, we have completed the request
if (request.status === 200 || request.status === 0 /*for ff bug*/ ) {
success(request.responseText, request);
} else { //if failed
try {
request.responseJSON = JSON.parse(request.responseText);
} catch (e) {
return false;
}
failure(request);
}
// hide the loader because the request has finished
done = true;
}
}
};
// send off the request
request.send(data);
});
return InitRequest;
};
// The "opt" variable also goes into place as the
// Cache reset
if (opt && typeof opt !== "string" && typeof opt !== "boolean") {
var DEFAULTS = {
type: "GET",
data: {},
cache: false,
success: function() {},
failure: function() {}
};
var o = $.extend(DEFAULTS, opt);
return AJAX(o.type, url, o.data, o.success, o.failure, o.cache);
} else {
return {
post: function(data, success, failure, cache) {
return AJAX("POST", url, data, success, failure, cache);
},
get: function(data, success, failure, cache) {
return AJAX("GET", url, data, success, failure, cache);
}
}
}
}
A little more information about sending data via AJAX
Data in your case should correspond with the ids:
{
0: {
trf: {
input1: "..",
input2: "..",
input3: ".."
}
},
1: {
trf: {
input1: "..",
input2: "..",
input3: ".."
}
}
}
The HTML part contains a textarea with a label.The user has to enter text and the form should be submitted and refreshed for the user to enter text again for say 5 more times. How can I do this using Javascript?
This is the html code:
<form name="myform" method="post">
<div class="form-group col-sm-5">
<label for="ques"><p id="p1">Question:</p></label>
<textarea class="form-control" rows="5" id="ques"></textarea>
</div>
</form>
<button type="button" class="btn" id="sub" onclick="func()">Next</button>
The javascript code:
var x=1;
document.getElementById("p1").innerHTML="Question"+x;
function func()
{
var frm = document.getElementsByName('myform')[0];
frm.submit();
frm.reset();
return false;
}
Here are two methods you can use. Both of these require you to add a submit button to your form, like this:
<form name="myform" method="post">
<div class="form-group col-sm-5">
<label for="ques"><p id="p1">Question:</p></label>
<textarea class="form-control" rows="5" id="ques"></textarea>
</div>
<!-- add this button -->
<input type="submit" value="Submit" class="btn">
</form>
<!-- no need for a <button> out here! -->
Method 1: sessionStorage
sessionStorage allows you to store data that is persistent across page reloads.
For me info, see the MDN docs on sessionStorage. This method requires no external libraries.
Note that in this method, your page is reloaded on submit.
window.onload = function() {
var myForm = document.forms.myform;
myForm.onsubmit = function(e) {
// get the submit count from sessionStorage OR default to 0
var submitCount = sessionStorage.getItem('count') || 0;
if (submitCount == 5) {
// reset count to 0 for future submissions
} else {
// increment the count
sessionStorage.setItem('count', submitCount + 1);
}
return true; // let the submission continue as normal
}
// this code runs each time the pages loads
var submitCount = sessionStorage.getItem('count') || 0;
console.log('You have submited the form ' + submitCount + ' times');
if (submitCount == 4) {
console.log("This will be the final submit! This is the part where you change the submit button text to say \"Done\", etc.");
}
};
Method 2: AJAX with jQuery
If you don't mind using jQuery, you can easily make AJAX calls to submit your form multiple times without reloading.
Note that in this example your page is not reloaded after submit.
window.onload = function() {
var myForm = document.forms.myform;
var submitCount = 0;
myForm.onsubmit = function(e) {
$.post('/some/url', $(myForm).serialize()).done(function(data) {
submitCount++;
});
console.log('You have submited the form ' + submitCount + ' times');
if (submitCount == 4) {
console.log("This will be the final submit! This is the part where you change the submit button text to say \"Done\", etc.");
}
e.preventDefault();
return false;
};
};
Hope this helps!
You shuld create an array and push the value of the textbox to the array in func().
We can create a template using a <script type="text/template>, then append it to the form each time the button is clicked.
const btn = document.getElementById('sub');
const appendNewTextArea = function() {
const formEl = document.getElementById('form');
const textareaTemplate = document.getElementById('textarea-template').innerHTML;
const wrapper = document.createElement('div');
wrapper.innerHTML = textareaTemplate;
formEl.appendChild(wrapper);
}
// Call the function to create the first textarea
appendNewTextArea();
btn.addEventListener('click', appendNewTextArea);
<form name="myform" method="post" id="form">
</form>
<button type="button" class="btn" id="sub">Next</button>
<script id="textarea-template" type="text/template">
<div class="form-group col-sm-5">
<label for="ques"><p id="p1">Question:</p></label>
<textarea class="form-control" rows="5" id="ques"></textarea>
</div>
</script>
I am using a simple jsp to populate a drop down box (with addresses as options) based on an input parameter (postcode) using ajax in javascript. The javascript code is able to pull the required data, and sets the options in the select element, but just after a fraction of second, all changes disappear and the jsp is back to its initial state. Can you help me in troubleshooting the cause of this behaviour? Thanks in advance.
main JSP code: testajx.jsp
<form name="testform" method="POST" action="testajx.jsp" >
<h1><%=a%> testing <b>Postcode Lookup</b></h1>
<br>
<br>
<input type="text" name="ziporpostalcode" size="10" maxlength="7" value="<%=ziporpostalcode%>"/>
<input type="text" name="ziporpostalcodetest" size="10" maxlength="7" value=""/>
<input type="hidden" name="searchPostCodeHidden" value="">
<input type="button" name="searchPostCode" value="Search" onclick="if(ziporpostalcode.value == ''){alert('enter postcode');}else {searchPostCodeHidden.value = 'TRUE'; this.form.submit();}">
<input type="hidden" name="searchAddressHidden" value="">
<input type="button" name="test" value="test" onclick="alert(userAddress.value);alert('<%=userAddress%>');">
<input type=image name="op_xxx" value="Search Address xxx" src="\jsp\htdocs\assets\images2011\buttons\search_address.gif" alt="Search Address" onclick="sendRequest('GET','testajax.jsp?ziporpostalcode='+ziporpostalcode.value)"href="#" />
<select name="userAddress" value="<%=userAddress%>" onchange="searchAddressHidden.value = userAddress.value; form.submit();">
<option>--- Select ---</option>
<%=addressOptions%>
</select>
<div id="ajax_res">a</div>
</body>
</form>
Results received from testajax.jsp:
<body>
<select name="userAddress">
<option>--- Select ---</option>
<%
String addressOptions = new String();
Picklist pl = new Picklist();
addressOptions = "";
String ziporpostalcode = request.getParameter("ziporpostalcode");
pl = PostcodeHandler.getAddressList(ziporpostalcode);
PicklistItem[] pli = pl.getItems();
//Iterator li = sAddressList.values().iterator();
for(int i=0; i<pl.getTotal(); i++)
{
addressOptions += "<option label=\""+pli[i].getPartialAddress()+"\" value=\""+pli[i].getMoniker()+"\">"+pli[i].getText()+"</option>";
session.setAttribute("addressOptions", addressOptions);
request.setAttribute("ziporpostalcode", ziporpostalcode);
request.setAttribute("searchPostCodeHidden", ziporpostalcode);
// addressOptions += "<option label='"+sAddressList.get(i).toString()+"' value='"+sAddressList.get(i).toString()+"'>"+sAddressList.get(i).toString()+"</option>";
}
String str="This is JSP string loading from JSP page in ajax, loading time :";
out.print(addressOptions);
%>
</select>
ajax javascript code is:
<script language="Javascript" type="text/javascript">
function createRequestObject(){
var req;
try {
// Firefox, Opera, Safari
req = new XMLHttpRequest();
} catch (e) {
// Internet Explorer
try {
//For IE 6
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
//For IE 5
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert('Your browser is not IE 5 or higher, or Firefox or Safari or Opera');
}
}
}
return req;
}
//Make the XMLHttpRequest Object
var http = createRequestObject();
function sendRequest(method, url){
if(method == 'get' || method == 'GET'){
http.open(method,url,true);
http.onreadystatechange = handleResponse;
http.send(null);
}
}
function handleResponse(){
if(http.readyState == 4 && http.status == 200){
var response = http.responseText;
if(response){
document.getElementById("ajax_res").innerHTML = response;
document.getElementById("ziporpostalcodetest").value = 'response';
document.getElementById("testform").action = 'testajax.jsp';
alert('received something from Ajax');
}
}
}
You're sending an ajax request in the onclick of an <input type="image"> submit button. However, you're not blocking the button's default behaviour when the onclick is finished. The button's default behaviour is namely submitting the form where it is sitting in. You need to block the button's default behaviour by returning false in the onclick.
So, change
<input type=image ... onclick="sendRequest('GET','testajax.jsp?ziporpostalcode='+ziporpostalcode.value)"href="#" />
to
<input type=image ... onclick="sendRequest('GET','testajax.jsp?ziporpostalcode='+ziporpostalcode.value); return false;"href="#" />
Unrelated to the concrete problem, you've severe design problems with this all. I'm not sure where you've learnt HTML, JSP and Ajax, but this all looks very 90's. Make sure that you're reading up to date resources. This may be a good starting point: How to use Servlets and Ajax?
Just tired to search an error in your code. Here is my (don't foget include jQuery core):
<div id="content"></div>
<script type="text/javascript">
function updateDivContent() {
var result = jQuery.ajax({
url: "your url",
type: "POST",
async: true,
cache: false,
data: // your form data, can use serialize from jquery
});
jQuery("div#content").html(result.responseText)
}
</script>
Im building a file upload with jQuery, but Im getting a jQuery error trying to set the attributes of the form:
$(document).ready(function () {
$("#formsubmit").click(function () {
var iframe = $('<iframe name="postframe" id="postframe" class="hidden" src="about:none" />');
$('div#iframe').append(iframe);
$('#theuploadform').attr("action", "/ajax/user.asmx/Upload")
$('#theuploadform').attr("method", "post")
$('#theuploadform').attr("userfile", $('#userfile').val())
$('#theuploadform').attr("enctype", "multipart/form-data")
$('#theuploadform').attr("encoding", "multipart/form-data")
$('#theuploadform').attr("target", "postframe")
$('#theuploadform').submit();
//need to get contents of the iframe
$("#postframe").load(
function () {
iframeContents = $("iframe")[0].contentDocument.body.innerHTML;
$("div#textarea").html(iframeContents);
}
);
}
);
<div id="uploadform">
<form id="theuploadform" action="">
<input id="userfile" name="userfile" size="50" type="file" />
<input id="formsubmit" type="submit" value="Send File" />
</form>
</div>
<div id="iframe" style="width: 0px; height: 0px; display: none;">
</div>
<div id="textarea">
</div>
I found the solution. This code works:
<script type="text/javascript">
$(document).ready(function () {
$("#formsubmit").click(function () {
var iframe = $('<iframe name="postiframe" id="postiframe" style="display: none"></iframe>');
$("body").append(iframe);
var form = $('#theuploadform');
form.attr("action", "/upload.aspx");
form.attr("method", "post");
form.attr("encoding", "multipart/form-data");
form.attr("enctype", "multipart/form-data");
form.attr("target", "postiframe");
form.attr("file", $('#userfile').val());
form.submit();
$("#postiframe").load(function () {
iframeContents = this.contentWindow.document.body.innerHTML;
$("#textarea").html(iframeContents);
});
return false;
});
});
</script>
<form id="theuploadform">
<input id="userfile" name="userfile" size="50" type="file" />
<input id="formsubmit" type="submit" value="Send File" />
</form>
<div id="textarea">
</div>
It's not an official plugin, however here's an example on how you could wrap the form's submitting logic into a plugin.
Example:
<form method="post" enctype="multipart/form-data">
<input name="file" type="file" />
<input type="text" name="test" />
<button type="submit">Submit</button>
</form>
<script>
$('form').submit(function (e) {
//prevent default submit
e.preventDefault();
//submit through frame
$(this).frameSubmit({
done: function (form, frame, options) {
console.log('done!');
},
fail: function (form, frame, options) {
console.log('fail!');
},
always: function (form, frame, options) {
console.log('always!');
}
//custom hasError implementation if needed
//by default if the frame's body HTML contains the text "unexpected error" or "server error"
//it is treated as an error
/*,hasError: function (frame) {
return false;
}*/
});
});
</script>
PLUGIN
!function ($, doc) {
var _frameCount = 0,
_callbackOptions = ['done', 'fail', 'always'],
_hasFailed = function (frame) {
var frameHtml = $(frame).contents().find('body').html();
return /(server|unexpected)\s+error/i.test(frameHtml);
},
_createFrame = function () {
return $('<iframe>').prop('name', 'jq-frame-submit-' + _frameCount++).hide().appendTo(doc.body);
};
$.fn.extend({
frameSubmit: function (options) {
return this.each(function () {
var deferred = $.Deferred(),
form = this,
initialTarget = form.target,
hasTarget = form.hasAttribute('target'),
hasFailed = options.hasFailed || _hasFailed,
//The initial frame load will fire a load event so we need to
//wait until it fires and then submit the form in order to monitor
//the form's submission state.
$frame = _createFrame().one('load', function () {
$frame.one('load', function () {
deferred[hasFailed(this) ? 'reject' : 'resolve'](form, this, options);
$frame.remove();
});
form.submit();
//restore initial target attribute's value
if (hasTarget) form.target = initialTarget;
else form.removeAttribute('target');
});
//attach handlers to the deferred
$.each(_callbackOptions, function (i, optName) {
options[optName] && deferred[optName](options[optName]);
});
//make sure the form gets posted the to iframe
form.target = $frame.prop('name');
});
}
});
}(jQuery, document);
Your form target should be the same as iframe name, for example:
<form target="frame"
action="http://posttestserver.com/post.php?dir=example"
method="post"
enctype="multipart/form-data">
<input name="file" type="file"/>
</form>
<iframe name="frame"></iframe>
And after this you can attach event to input button to listen for 'change'.
Furthemore you can get progress from server using jsonp and all of this will work in any browser event IE3+. Something like this:
$('input').change(function () {
$('form').submit();
});
$.getJSON('/echo/jsonp/?callback=?', function(e, progress) {
console.log(progress);
});
This is a good plugin to upload files using ajax
http://jquery.malsup.com/form/#file-upload
You know instead of fetching the same item multiple times, why not just reuse it:
var form = $('#theuploadform');
form.attr("action", "/ajax/user.asmx/Upload");
form.attr("method", "post");
// and so on
What kind of error are you having? can you post it?
UPDATE
Since you cannot set the attribute yourself here is a work around:
Put the form in an iframe, and attach an onchange event to the input button.
when the user select a file, you trigger the necessary code to upload the file (submit), then the parent window can close the iframe.