servlet not responding back to ajax request - java

servlet is not sending back response to ajax code. Plaease help!!!
html code, here output should be printed
this is ajax code in javascript
<script language="javascript">
reqObj=null;
function getPrice(){
if(window.XMLHttpRequest){
reqObj=new XMLHttpRequest();
}else {
reqObj=new ActiveXObject("Microsoft.XMLHTTP");
}
reqObj.onreadystatechange=process;
var area = document.getElementById('product').value;
var fType= document.getElementById('size').value;
reqObj.open("POST","./getPricefromSize?pro="+area+"&size="+fType,true);
reqObj.send(null);
}
function process1(){
if(reqObj.readyState==4){
var prce=reqObj.responseText;
document.getElementById("price").innerHTML=prce;
}
}
</script>
this is my servlet code:
String str=request.getParameter("pro");
String str1=request.getParameter("size");
PrintWriter out1=response.getWriter();
System.out.println("pro: "+str+"size: "+str1);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:linpaws","system","oracle");
st=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
rs=st.executeQuery("select price from labpro where usernm='"+labid+"' and product='"+str+"' and sze='"+str1+"'");
rs.first();
price=rs.getString(1);
System.out.println("price"+price);
out1.write(price);
rs.close();
st.close();
output is printed in console. But not showing in ajax call

You are missing some bits out of your code:
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");
http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp should put you on the right track.
Another reason its not working is your assigning process to your onreadystatechange e.g
onreadystatechange=process but process must exactly match the name of the function your assigning which in your case is process1 so the code would become reqObj.onreadystatechange=process1.

Related

Spring how to refresh the page when I received a transaction?

I work with Spring Mvc app to develop a bitcoin wallet and I have the controller definition,
#RequestMapping(value = "/")
public String showBitcoinWallet() {
return "index";
}
This returns the index.jsp page provides the relevant infos,
Till the moment the app is not synchronized to the blockchain, it will refresh in every 3000 ms from the script,
<html>
<body>
<!- some code ->
<!- some code ->
</body>
<script>
<% if(!model.isSyncFinished()) {%>
setTimeout(function () {
window.location.reload(1);
}, 3000);
<% }%>
</script>
</html>
For the sending operation, a pop-up opens and the user execute the submission. This operation refresh the page and updates the info(e.g balance, address etc). In the instance of receiving, the page is not refreshed and only updates if I manually refresh.
I need to refresh the page after the user received the money.
I have a method that returns boolean of the receive execution operation,
public static boolean isMoneyReceived() {
try {
WalletMain.bitcoin.wallet().addEventListener(new AbstractWalletEventListener() {
#Override
public void onCoinsReceived(Wallet w, Transaction tx, Coin prevBalance, Coin newBalance) {
// Runs in the dedicated "user thread".
//
// The transaction "tx" can either be pending, or included into a block (we didn't see the broadcast).
Coin value = tx.getValueSentToMe(w);
// System.out.println("Received tx for " + value.toFriendlyString() + ": " + tx);
// System.out.println("Transaction will be forwarded after it confirms.");
}
});
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
return false;
}
}
So, the intension will be to write code the in the <script> that if the isMoneyReceived returns true, then, I would need to refresh the page. In that case, I may need to put the method in an iteration say, while and keep on calling with an if condition.
There might be 2nd option to have done it completely in the controller. I have tried to do it in the index.jsp page inside the <script> tag with no success,
<% while(true) {%>
<% boolean moneyReceived = BitcoinWalletController.isMoneyReceived(); %>
<% if(moneyReceived) {%>
// tried to print something ..
<% System.out.println("-----------------------"); %>
<% System.out.println("Hello, Money Received"); %>
<% System.out.println("-----------------------"); %>
<% moneyReceived = false; %>
<% }%>
<%}%>
I ended up getting the error,
HTTP Status [500] – [Internal Server Error]
Type Exception Report
Message java.lang.ClassNotFoundException: org.apache.jsp.WEB_002dINF.jsps.index_jsp
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
org.apache.jasper.JasperException: java.lang.ClassNotFoundException: org.apache.jsp.WEB_002dINF.jsps.index_jsp
org.apache.jasper.servlet.JspServletWrapper.getServlet(JspServletWrapper.java:176)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:380)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
How to solve the problem? As mentioned earlier, if i can redirect the page from the Spring controller, that would be fine as well.
The problem with your code is that jsp pages are rendered on the server. So, putting a while loop will pretty much prevent the page from ever getting to the clients browser (and being displayed).
Therefore, the way I suggest is to use an AJAX call to the isMoneyReceived() method and then check the return value using a script.
This is a code sample with jQuery ajax get request:
$("button").click(function(){
$.get("yourTargetInterface", function(data, status){
//your processing code here, with the variable "data" being the response to your request; in this case true or false
});
});
yourTargetInterface should be the interface to your method (e.g. through a servlet, web service, etc.).
You can replace $("button").click with a timeout (e.g. every 3 secs).
Then you can process it with a script and setup the application logic accordingly.

Calling Java class from JSP button onclick

I am trying to to call a Java class when a button gets clicked from JSP. inside my JSP file I have the following:
<%
Object name = session.getAttribute("name");
Object ext = session.getAttribute("ext");
DBOps ops = new DBOps();
ReturnGetDisplayInfo GDI = ops.getDisplayInfo(ext);
%>
I have a method in DBOps that will delete a certain field so I added a button to teh table that displays the information and now I am trying to call the delete method when the button is clicked. so I tried doing the following but it did not work.
<td><button onclick=<% ops.delete(ext); %>>Delete</button></td>
I was looking at some examples that utilize javascript but it uses defiend functions in teh script rather than calling the Java class.
Thanks in advance
You can't do that directly. You need a roundtrip to the server.
The best option for that is AJAX:
make a servlet that handles performs the delete request when a certain url is invoked
use jQuery (or native XmlHttpRequest) to invoke that url
(DWR - direct web remoting is also an option, which is implemented using AJAX)
One example of my code, in javascript and ajax, if it can help you:
On my jsp i have a onClick"changeTimeZone(org)"
Javascript:
function changeTimeZone(org)
{
//Prepare a new ajaxRequest.
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
//state 4 is response ready.
//Status 200 is page found.
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//fill the timezone field with the reponse of my servlet.
document.getElementById('timeZoneText').value = xmlhttp.responseText;
}
};
//send an ajax request.
//Go to my servlet
xmlhttp.open('GET','mainServlet?command=ajax.ChangeTimeZone&Org=' + org.value, true);
xmlhttp.send();
}

How to show value from database to jsp without refreshing the page using ajax

I am an Ajax fresher
Ajax
function ajaxFunction() {
if(xmlhttp) {
var txtname = document.getElementById("txtname");
xmlhttp.open("POST","Namelist",true);
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("txtname=" + txtname.value);
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
document.getElementById("message").innerHTML=xmlhttp.responseText;
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
jsp
<form name="fname" action="Namellist" method="post">
Select Category :
<select name="txtname" id="txtname">
<option value="Hindu">Hindu</option>
<option value="Muslim">Muslim</option>
<option value="Christian">Christian</option>
</select>
<input type="button" value="Show" id="sh" onclick="ajaxFunction();">
<div id="message">here i want to display name</div><div id="message1">here i want to display meaning</div>
</form>
servlet
String ct=null;
ct=request.getParameter("txtname");
Connection con=null;
ResultSet rs=null;
Statement st=null;
try{
con=Dbconnection.getConnection();
PreparedStatement ps=con.prepareStatement("select name meaning from (select * from namelist order by dbms_random.value)where rownum<=20 and category='+ct+'" );
rs=ps.executeQuery();
out.println("name" + rs);
**Here I have confusion,**
}
catch(Exception e)
{
System.out.println(e);
}
How can i diaplay servlet value to jsp.
Please help me? or please provide some good tutorial links.
You have to make below changes :-
In Servlet :-
Set the response content type as:- response.setContentType("text/xml"); in top section of the servlet. By setting this we can send the response in XML format and while retrieving it on JSP we will get it based on tag name of the XML.
Do whatever operation you want in servlet...
Save the value for ex-
String uname=";
uname="hello"; //some operation
//create one XML string
String sendThis="<?xml version='1.0'?>"
+"<Maintag>"
+"<Subtag>"
+"<unameVal>"+uname+"</unameVal>"
+"</Subtag>"
+"</Maintag>"
out.print(sendThis);
Now we'll go to JSP page where we've to display data.
function getXMLObject() //XML OBJECT
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
function ajaxFunction() {
if(xmlhttp) {
xmlhttp.open("GET","NameList",true); //NameList will be the servlet name
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(null);
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
getVal();
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
function getVal()
{
var xmlResp=xmlhttp.responseText;
try{
if(xmlResp.search("Maintag")>0 )
{
var x=xmlhttp.responseXML.documentElement.getElementsByTagName("Subtag");
var xx=x[0].getElementsByTagName("unameVal");
var recievedUname=xx[0].firstChild.nodeValue;
document.getElementById("message").innerText=recievedUname;//here
}
}catch(err2){
alert("Error in getting data"+err2);
}
}
And here you are done. :)
1.In servlet code
PrintWriter output = response.getWriter();
String result = "value";
writer.write(result);
writer.close()
2. Why you don't use jquery ?
You can replace your code on -
$.post('url', function(data) {
$('#message1').html(data);
});
query post example
Probably off the hook but might be useful, rather than putting up all the javascript for Ajax call use some javascript library preferably jQuery for making the Ajax call.
Any javascript library you use will help you make the code compact and concise and will also help you maintain cross browser compatibility.
If you planning to write all the XHTTP code yourself, you might end up spending a lot of time for fixing cross browser issues and your code will have a lots of hacks rather than the actual business logic.
Also, using library like jQuery will also achieve the same stuff with less number of lines of code.
Hope that helps.

How to call servlet from javascript

Servlet Configuration in web.xml
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>DataEntry</servlet-name>
<servlet-class>com.ctn.origin.connection.DataEntry</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DataEntry</servlet-name>
<url-pattern>/dataentry</url-pattern>
</servlet-mapping>
Javascript :
<script type="text/javascript">
function unloadEvt() {
document.location.href='/test/dataentry';
}
</script>
But using this javascript can't call my servlet.
Is there any error ? how to call servlet ?
From your original question:
document.location.href="/dataentry";
The leading slash / in the URL will take you to the domain root.
So if the JSP page containing the script is running on
http://localhost:8080/contextname/page.jsp
then your location URL will point to
http://localhost:8080/dataentry
But you actually need
http://localhost:8080/contextname/dataentry
So, fix the URL accordingly
document.location.href = 'dataentry';
// Or
document.location.href = '/contextname/dataentry';
// Or
document.location.href = '${pageContext.request.contextPath}/dataentry';
Apart from that, the function name unloadEvt() suggests that you're invoking the function during onunload or onbeforeunload. If this is true, then you should look for another solution. The request is not guaranteed to ever reach the server. This depends on among others the browser used. How to solve it properly depends on the sole functional requirement which is not clear from the question.
You can try this if you are using jQuery. It's simple:
<script>
$(window).unload(function() {
document.location.href='/test/dataentry';
});
</script>
This can be done using ajax
<script type="text/javascript">
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", "/testmail/dataentry", true);
xmlhttp.send();
}
</script>

How do I know if form submission is successful?

I have a form, basically to upload a file. I am submitting the form twice, 1 without multipart and the 2nd 1 with multipart.
<input type="button" tabindex="5" value="Create" id="btnS" class="btn" onClick="submitForm(this.form,'/test/upload'); return false;" />
//1st submission
form.setAttribute("action",url_action);
form.setAttribute("method","post");
form.submit();
//2nd submission
form.setAttribute("action",url_action);
form.setAttribute("method","post");
form.setAttribute("enctype","multipart/form-data");
form.setAttribute("encoding","multipart/form-data");
form.submit();
but instead I want to 1st check if the 1st form submission is successful then go for 2nd submition
Edited after referring #Vern
var postString = getPostString();
var client=new XMLHttpRequest();
client.onreadystatechange=handler(form,url_action);
client.open("POST",url_action,true);
client.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
client.setRequestHeader("Content-length", postString.length);
client.setRequestHeader("Connection", "close");
client.send(postString);
function handler(form,url_action)
{
if(this.readyState == 4 && this.status == 200) {
//Here submitted is the text that I receive from the servlet If 1st submit is successful
if (xmlhttp.responseText == "submitted"){
secondSend(form,url_action);
} else {
alert("Not good!");
}
}
}
function getPostString()
{
}
function secondSend(form,url_action)
{
form.setAttribute("action",url_action);
form.setAttribute("method","post");
form.setAttribute("enctype","multipart/form-data");
form.setAttribute("encoding","multipart/form-data");
form.submit();
}
Here is my servlet part. where I am identifying if its multipart or not. If not store the resultType to a session variable then return submitted,
Now I want to check for this "submitted" or similar and go for submitting the form 2nd time.
2nd Form submission: Here I will check if its multipart again, and check the session variable and go for CRUD. (This IdentifyNow is basically a kind of request modulator)
public String identifyNow()throws ServletException, java.io.IOException
{
UploadXmlAgent uploadAgent;
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
System.out.println("\n\n*********************************\nisMultipart: "+isMultipart);
if(isMultipart)
{
session=request.getSession(false);
System.out.println("\nThis is multipart and isNew"+session.isNew());
if(session!=null)
{
System.out.println("\ninside session");
requestType=session.getAttribute("resultType").toString();
//Identified based on requestType, instantiate appropriate Handler
//session.invalidate();
if(requestType.equals("Create"))
{
uploadAgent=new UploadXmlAgent(realPath,request,paramMap);
uploadAgent.retrieveXml();
return uploadAgent.uploadXml();
}
else if(requestType.equals("Update"))
{
}
else if(requestType.equals("Delete"))
{
}
}
else
{
return "Session is null";
}
}
else
{
System.out.println("\nNot a multipart");
paramMap=request.getParameterMap();
if (paramMap == null)
throw new ServletException(
"getParameterMap returned null in: " + getClass().getName());
iterator=paramMap.entrySet().iterator();
System.out.println("\n"+paramMap.size());
while(iterator.hasNext())
{
Map.Entry me=(Map.Entry)iterator.next();
if(me.getKey().equals("resultType"))
{
String[] arr=(String[])me.getValue();
requestType=arr[0];
System.out.println("Inside returntype: "+requestType);
}
}
session=request.getSession(true);
session.setAttribute("returntype", requestType);
System.out.println("Session.isNew="+session.isNew());
return "submitted";
}
return "noCreate";
}
Here is Javascript function which is used to submit form twice, look for micoxUpload() function.
/* standard small functions */
function $m(quem){
return document.getElementById(quem)
}
function remove(quem){
quem.parentNode.removeChild(quem);
}
function addEvent(obj, evType, fn){
// elcio.com.br/crossbrowser
if (obj.addEventListener)
obj.addEventListener(evType, fn, true)
if (obj.attachEvent)
obj.attachEvent("on"+evType, fn)
}
function removeEvent( obj, type, fn ) {
if ( obj.detachEvent ) {
obj.detachEvent( 'on'+type, fn );
} else {
obj.removeEventListener( type, fn, false ); }
}
/* THE UPLOAD FUNCTION */
function micoxUpload(form,url_action,id_element,html_show_loading,html_error_http){
/******
* micoxUpload - Submit a form to hidden iframe. Can be used to upload
* Use but dont remove my name. Creative Commons.
* Versão: 1.0 - 03/03/2007 - Tested no FF2.0 IE6.0 e OP9.1
* Author: Micox - Náiron JCG - elmicoxcodes.blogspot.com - micoxjcg#yahoo.com.br
* Parametros:
* form - the form to submit or the ID
* url_action - url to submit the form. like action parameter of forms.
* id_element - element that will receive return of upload.
* html_show_loading - Text (or image) that will be show while loading
* html_error_http - Text (or image) that will be show if HTTP error.
*******/
//testing if 'form' is a html object or a id string
form = typeof(form)=="string"?$m(form):form;
var erro="";
if(form==null || typeof(form)=="undefined"){ erro += "The form of 1st parameter does not exists.\n";}
else if(form.nodeName.toLowerCase()!="form"){ erro += "The form of 1st parameter its not a form.\n";}
if($m(id_element)==null){ erro += "The element of 3rd parameter does not exists.\n";}
if(erro.length>0) {
alert("Error in call micoxUpload:\n" + erro);
return;
}
//creating the iframe
var iframe = document.createElement("iframe");
iframe.setAttribute("id","micox-temp");
iframe.setAttribute("name","micox-temp");
iframe.setAttribute("width","0");
iframe.setAttribute("height","0");
iframe.setAttribute("border","0");
iframe.setAttribute("style","width: 0; height: 0; border: none;");
//add to document
form.parentNode.appendChild(iframe);
window.frames['micox-temp'].name="micox-temp"; //ie sucks
//add event
var carregou = function() {
removeEvent( $m('micox-temp'),"load", carregou);
var cross = "javascript: ";
cross += "window.parent.$m('" + id_element + "').innerHTML = document.body.innerHTML; void(0); ";
$m(id_element).innerHTML = html_error_http;
$m('micox-temp').src = cross;
//del the iframe
setTimeout(function(){ remove($m('micox-temp'))}, 250);
}
addEvent( $m('micox-temp'),"load", carregou)
//properties of form
/*form.setAttribute("target","micox-temp");
form.setAttribute("action",url_action);
form.setAttribute("method","post");*/
//form.submit();
var postString = getPostString();
var client;
if (window.XMLHttpRequest){ // IE7+, Firefox, Chrome, Opera, Safari
client=new XMLHttpRequest();
} else { // IE6, IE5
client=new ActiveXObject("Microsoft.XMLHTTP");
}
//client.onreadystatechange=handler(form,url_action);
client.open("POST",url_action,true);
client.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
client.setRequestHeader("Content-length", postString.length);
client.setRequestHeader("Connection", "close");
client.onreadystatechange = function(){
if (client.readyState==4 && client.status==200){
alert(client.responseText); //This gives back my text from servlet
secondSend(form,url_action);
}
};
client.send($postStr);
alert("1st request send");
//secondSend(form,url_action);
//while loading
if(html_show_loading.length > 0){
$m(id_element).innerHTML = html_show_loading;
}
function getPostString()
{
$postStr=document.getElementsByTagName("confname");
$postStr+=document.getElementsByTagName("returntype");
return $postStr;
}
function secondSend(form,url_action)
{
form.setAttribute("target","micox-temp");
form.setAttribute("action",url_action);
form.setAttribute("method","post");
form.setAttribute("enctype","multipart/form-data");
form.setAttribute("encoding","multipart/form-data");
form.submit();
if(html_show_loading.length > 0){
$m(id_element).innerHTML = html_show_loading;
}
}
}
submit() does not have a return value and as such you are not able to check the outcome of the submission just based on your code above.
However, the common way to do it is actually to use Ajax and use a function to set a flag. That way, you can check if the form is successfully submitted. Not to mention, with the server reply, you can further validate if the form has been transmitted correctly to the server :)
Hope it helped. Cheers!
The following code should give you an idea of how to do it:
function first_send(){
// Local Variable
var xmlhttp;
// Create Object
if (window.XMLHttpRequest){ // IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
// Set Function
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
// (1) Check reply from server if request has been successfully
// received
// (2) Set flag / Fire-off next function to send
// Example
if (xmlhttp.responseText == "ReceiveSuccess"){
secondSend();
} else {
// Error handling here
}
}
}
// Gets the first set of Data you want to send
var postString = getPostString();
// Send
xmlhttp.open("POST","form1.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", postString.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(postString);
}
And you'll need:
function getPostString(){
// Collect data from your form here
}
function secondSend(){
// You can create this function and post like above
// or just do a direct send like your code did
}
Hope it helps (:
This code ought to do the trick, but be sure to fill up with the HTML form that you're using! Also, put the first form in a submission if you require:
<script type="text/javascript">
var postString = getPostString();
var client = new XMLHttpRequest(); // You shouldn't create it this way.
// Open Connection and set the necessary
client.open("POST",url_action,true);
client.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
client.setRequestHeader("Content-length", postString.length);
client.setRequestHeader("Connection", "close");
// Create function
client.onreadystatechange = function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
if (xmlhttp.responseText == "Success") {
secondSend();
} else {
alert('In Error');
}
}
};
client.send(postString);
function getPostString()
{
// Get your postString data from your form here
// Return your Data to post
return $postStr;
}
function secondSend()
{
// Make sure you fill up your form before you post
form.setAttribute("action",url_action);
form.setAttribute("method","post");
form.setAttribute("enctype","multipart/form-data");
form.setAttribute("encoding","multipart/form-data");
form.submit();
}
</script>
I am sharing the ajax way of doing it apart from the regular XMLHttpRequest by #Vern
/*CALLING 1st SUBMIT*/
$(function() {
$("#submitButton").click(callme);
function callme() {
var form=document.forms["yourFormID"];
$.ajax({
type: "POST",
url: "/upload",
data: {resulttype: $('#resulttype').val()},
async:false,
complete: function(msg){
micoxUpload(form,'/upload','postUploadInformation','Loading...','Crap! something went wrong'); return false;
}
});
}
});
/* THE UPLOAD FUNCTION */
function micoxUpload(form,url_action,id_element,html_show_loading,html_error_http){
/******
* micoxUpload - Submit a form to hidden iframe. Can be used to upload
* Use but dont remove my name. Creative Commons.
* Versão: 1.0 - 03/03/2007 - Tested no FF2.0 IE6.0 e OP9.1
* Author: Micox - Náiron JCG - elmicoxcodes.blogspot.com - micoxjcg#yahoo.com.br
* Parametros:
* form - the form to submit or the ID
* url_action - url to submit the form. like action parameter of forms.
* id_element - element that will receive return of upload.
* html_show_loading - Text (or image) that will be show while loading
* html_error_http - Text (or image) that will be show if HTTP error.
*******/
//testing if 'form' is a html object or a id string
form = typeof(form)=="string"?$m(form):form;
var erro="";
if(form==null || typeof(form)=="undefined"){ erro += "The form of 1st parameter does not exists.\n";}
else if(form.nodeName.toLowerCase()!="form"){ erro += "The form of 1st parameter its not a form.\n";}
if($m(id_element)==null){ erro += "The element of 3rd parameter does not exists.\n";}
if(erro.length>0) {
alert("Error in call micoxUpload:\n" + erro);
return;
}
//creating the iframe
var iframe = document.createElement("iframe");
iframe.setAttribute("id","micox-temp");
iframe.setAttribute("name","micox-temp");
iframe.setAttribute("width","0");
iframe.setAttribute("height","0");
iframe.setAttribute("border","0");
iframe.setAttribute("style","width: 0; height: 0; border: none;");
//add to document
form.parentNode.appendChild(iframe);
window.frames['micox-temp'].name="micox-temp"; //ie sucks
//add event
var carregou = function() {
removeEvent( $m('micox-temp'),"load", carregou);
var cross = "javascript: ";
cross += "window.parent.$m('" + id_element + "').innerHTML = document.body.innerHTML; void(0); ";
$m(id_element).innerHTML = html_error_http;
$m('micox-temp').src = cross;
//del the iframe
setTimeout(function(){ remove($m('micox-temp'))}, 250);
}
addEvent( $m('micox-temp'),"load", carregou)
secondSend(form,url_action);
//while loading
if(html_show_loading.length > 0){
$m(id_element).innerHTML = html_show_loading;
}
function secondSend(form,url_action)
{
form.setAttribute("target","micox-temp");
form.setAttribute("action",url_action);
form.setAttribute("method","post");
form.setAttribute("enctype","multipart/form-data");
form.setAttribute("encoding","multipart/form-data");
form.submit();
if(html_show_loading.length > 0){
$m(id_element).innerHTML = html_show_loading;
}
}
}

Categories

Resources