Stop reload for ajax submitted form - javascript
My html of form is like this
<form id="form" method="post" action="func.php">
<table> <!--- DATA HERE --> </table>
<input type="submit" value="Submit" id="set" />
</form>
I want to use javascript to post the data, my javascript is like this
$('#set').live('click', function () {
$('.setForm').attr('action', '');
var setData = $('.setForm').serialize();
$.ajax({
type: 'post',
url: 'func.php',
data: setData,
success: function(response) {
$('#status').fadeIn('500').text('Loading..');
}
});
});
but i am getting an error i dont know what error it is, (It is not visible in console) i have Break on errors enabled in firebug which returns
(function(){var R=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?/g,L=0,H=Object.prototype.toString;var F=function(Y,U,ab,ac){ab=ab||[];U=U||document;if(U.nodeType!==1&&U.nodeType!==9){return[]}if(!Y||typeof Y!=="string"){return ab}var Z=[],W,af,ai,T,ad,V,X=true;R.lastIndex=0;while((W=R.exec(Y))!==null){Z.push(W[1]);if(W[2]){V=RegExp.rightContext;break}}if(Z.length>1&&M.exec(Y)){if(Z.length===2&&I.relative[Z[0]]){af=J(Z[0]+Z[1],U)}else{af=I.relative[Z[0]]?[U]:F(Z.shift(),U);while(Z.length){Y=Z.shift();if(I.relative[Y]){Y+=Z.shift()}af=J(Y,af)}}}else{var ae=ac?{expr:Z.pop(),set:E(ac)}:F.find(Z.pop(),Z.length===1&&U.parentNode?U.parentNode:U,Q(U));af=F.filter(ae.expr,ae.set);if(Z.length>0){ai=E(af)}else{X=false}while(Z.length){var ah=Z.pop(),ag=ah;if(!I.relative[ah]){ah=""}else{ag=Z.pop()}if(ag==null){ag=U}I.relative[ah](ai,ag,Q(U))}}if(!ai){ai=af}if(!ai){throw"Syntax error, unrecognized expression: "+(ah||Y)}if(H.call(ai)==="[object Array]"){if(!X){ab.push.apply(ab,ai)}else{if(U.nodeType===1){for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&(ai[aa]===true||ai[aa].nodeType===1&&K(U,ai[aa]))){ab.push(af[aa])}}}else{for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&ai[aa].nodeType===1){ab.push(af[aa])}}}}}else{E(ai,ab)}if(V){F(V,U,ab,ac);if(G){hasDuplicate=false;ab.sort(G);if(hasDuplicate){for(var aa=1;aa<ab.length;aa++){if(ab[aa]===ab[aa-1]){ab.splice(aa--,1)}}}}}return ab};F.matches=function(T,U){return F(T,null,null,U)};F.find=function(aa,T,ab){var Z,X;if(!aa){return[]}for(var W=0,V=I.order.length;W<V;W++){var Y=I.order[W],X;if((X=I.match[Y].exec(aa))){var U=RegExp.leftContext;if(U.substr(U.length-1)!=="\\"){X[1]=(X[1]||"").replace(/\\/g,"");Z=I.find[Y](X,T,ab);if(Z!=null){aa=aa.replace(I.match[Y],"");break}}}}if(!Z){Z=T.getElementsByTagName("*")}return{set:Z,expr:aa}};F.filter=function(ad,ac,ag,W){var V=ad,ai=[],aa=ac,Y,T,Z=ac&&ac[0]&&Q(ac[0]);while(ad&&ac.length){for(var ab in I.filter){if((Y=I.match[ab].exec(ad))!=null){var U=I.filter[ab],ah,af;T=false;if(aa==ai){ai=[]}if(I.preFilter[ab]){Y=I.preFilter[ab](Y,aa,ag,ai,W,Z);if(!Y){T=ah=true}else{if(Y===true){continue}}}if(Y){for(var X=0;(af=aa[X])!=null;X++){if(af){ah=U(af,Y,X,aa);var ae=W^!!ah;if(ag&&ah!=null){if(ae){T=true}else{aa[X]=false}}else{if(ae){ai.push(af);T=true}}}}}if(ah!==g){if(!ag){aa=ai}ad=ad.replace(I.match[ab],"");if(!T){return[]}break}}}if(ad==V){if(T==null){throw"Syntax error, unrecognized expression: "+ad}else{break}}V=ad}return aa};var I=F.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF_-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF_-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*_-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF_-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(T){return T.getAttribute("href")}},relative:{"+":function(aa,T,Z){var X=typeof T==="string",ab=X&&!/\W/.test(T),Y=X&&!ab;if(ab&&!Z){T=T.toUpperCase()}for(var W=0,V=aa.length,U;W<V;W++){if((U=aa[W])){while((U=U.previousSibling)&&U.nodeType!==1){}aa[W]=Y||U&&U.nodeName===T?U||false:U===T}}if(Y){F.filter(T,aa,true)}},">":function(Z,U,aa){var X=typeof U==="string";if(X&&!/\W/.test(U)){U=aa?U:U.toUpperCase();for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){var W=Y.parentNode;Z[V]=W.nodeName===U?W:false}}}else{for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){Z[V]=X?Y.parentNode:Y.parentNode===U}}if(X){F.filter(U,Z,true)}}},"":function(W,U,Y){var V=L++,T=S;if(!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("parentNode",U,V,W,X,Y)},"~":function(W,U,Y){var V=L++,T=S;if(typeof U==="string"&&!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("previousSibling",U,V,W,X,Y)}},find:{ID:function(U,V,W){if(typeof V.getElementById!=="undefined"&&!W){var T=V.getElementById(U[1]);return T?[T]:[]}},NAME:function(V,Y,Z){if(typeof Y.getElementsByName!=="undefined"){var U=[],X=Y.getElementsByName(V[1]);for(var W=0,T=X.length;W<T;W++){if(X[W].getAttribute("name")===V[1]){U.push(X[W])}}return U.length===0?null:U}},TAG:function(T,U){return U.getElementsByTagName(T[1])}},preFilter:{CLASS:function(W,U,V,T,Z,aa){W=" "+W[1].replace(/\\/g,"")+" ";if(aa){return W}for(var X=0,Y;(Y=U[X])!=null;X++){if(Y){if(Z^(Y.className&&(" "+Y.className+" ").indexOf(W)>=0)){if(!V){T.push(Y)}}else{if(V){U[X]=false}}}}return false},ID:function(T){return T[1].replace(/\\/g,"")},TAG:function(U,T){for(var V=0;T[V]===false;V++){}return T[V]&&Q(T[V])?U[1]:U[1].toUpperCase()},CHILD:function(T){if(T[1]=="nth"){var U=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(T[2]=="even"&&"2n"||T[2]=="odd"&&"2n+1"||!/\D/.test(T[2])&&"0n+"+T[2]||T[2]);T[2]=(U[1]+(U[2]||1))-0;T[3]=U[3]-0}T[0]=L++;return T},ATTR:function(X,U,V,T,Y,Z){var W=X[1].replace(/\\/g,"");if(!Z&&I.attrMap[W]){X[1]=I.attrMap[W]}if(X[2]==="~="){X[4]=" "+X[4]+" "}return X},PSEUDO:function(X,U,V,T,Y){if(X[1]==="not"){if(X[3].match(R).length>1||/^\w/.test(X[3])){X[3]=F(X[3],null,null,U)}else{var W=F.filter(X[3],U,V,true^Y);if(!V){T.push.apply(T,W)}return false}}else{if(I.match.POS.test(X[0])||I.match.CHILD.test(X[0])){return true}}return X},POS:function(T){T.unshift(true);return T}},filters:{enabled:function(T){return T.disabled===false&&T.type!=="hidden"},disabled:function(T){return T.disabled===true},checked:function(T){return T.checked===true},selected:function(T){T.parentNode.selectedIndex;return T.selected===true},parent:function(T){return !!T.firstChild},empty:function(T){return !T.firstChild},has:function(V,U,T){return !!F(T[3],V).length},header:function(T){return/h\d/i.test(T.nodeName)},text:function(T){return"text"===T.type},radio:function(T){return"radio"===T.type},checkbox:function(T){return"checkbox"===T.type},file:function(T){return"file"===T.type},password:function(T){return"password"===T.type},submit:function(T){return"submit"===T.type},image:function(T){return"image"===T.type},reset:function(T){return"reset"===T.type},button:function(T){return"button"===T.type||T.nodeName.toUpperCase()==="BUTTON"},input:function(T){return/input|select|textarea|button/i.test(T.nodeName)}},setFilters:{first:function(U,T){return T===0},last:function(V,U,T,W){return U===W.length-1},even:function(U,T){return T%2===0},odd:function(U,T){return T%2===1},lt:function(V,U,T){return U<T[3]-0},gt:function(V,U,T){return U>T[3]-0},nth:function(V,U,T){return T[3]-0==U},eq:function(V,U,T){return T[3]-0==U}},filter:{PSEUDO:function(Z,V,W,aa){var U=V[1],X=I.filters[U];if(X){return X(Z,W,V,aa)}else{if(U==="contains"){return(Z.textContent||Z.innerText||"").indexOf(V[3])>=0}else{if(U==="not"){var Y=V[3];for(var W=0,T=Y.length;W<T;W++){if(Y[W]===Z){return false}}return true}}}},CHILD:function(T,W){var Z=W[1],U=T;switch(Z){case"only":case"first":while(U=U.previousSibling){if(U.nodeType===1){return false}}if(Z=="first"){return true}U=T;case"last":while(U=U.nextSibling){if(U.nodeType===1){return false}}return true;case"nth":var V=W[2],ac=W[3];if(V==1&&ac==0){return true}var Y=W[0],ab=T.parentNode;if(ab&&(ab.sizcache!==Y||!T.nodeIndex)){var X=0;for(U=ab.firstChild;U;U=U.nextSibling){if(U.nodeType===1){U.nodeIndex=++X}}ab.sizcache=Y}var aa=T.nodeIndex-ac;if(V==0){return aa==0}else{return(aa%V==0&&aa/V>=0)}}},ID:function(U,T){return U.nodeType===1&&U.getAttribute("id")===T},TAG:function(U,T){return(T==="*"&&U.nodeType===1)||U.nodeName===T},CLASS:function(U,T){return(" "+(U.className||U.getAttribute("class"))+" ").indexOf(T)>-1},ATTR:function(Y,W){var V=W[1],T=I.attrHandle[V]?I.attrHandle[V](Y):Y[V]!=null?Y[V]:Y.getAttribute(V),Z=T+"",X=W[2],U=W[4];return T==null?X==="!=":X==="="?Z===U:X==="*="?Z.indexOf(U)>=0:X==="~="?(" "+Z+" ").indexOf(U)>=0:!U?Z&&T!==false:X==="!="?Z!=U:X==="^="?Z.indexOf(U)===0:X==="$="?Z.substr(Z.length-U.length)===U:X==="|="?Z===U||Z.substr(0,U.length+1)===U+"-":false},POS:function(X,U,V,Y){var T=U[2],W=I.setFilters[T];if(W){return W(X,V,U,Y)}}}};var M=I.match.POS;for(var O in I.match){I.match[O]=RegExp(I.match[O].source+/(?![^\[]*\])(?![^\(]*\))/.source)}var E=function(U,T){U=Array.prototype.slice.call(U);if(T){T.push.apply(T,U);return T}return U};try{Array.prototype.slice.call(document.documentElement.childNodes)}catch(N){E=function(X,W){var U=W||[];if(H.call(X)==="[object Array]"){Array.prototype.push.apply(U,X)}else{if(typeof X.length==="number"){for(var V=0,T=X.length;V<T;V++){U.push(X[V])}}else{for(var V=0;X[V];V++){U.push(X[V])}}}return U}}var G;if(document.documentElement.compareDocumentPosition){G=function(U,T){var V=U.compareDocumentPosition(T)&4?-1:U===T?0:1;if(V===0){hasDuplicate=true}return V}}else{if("sourceIndex" in document.documentElement){G=function(U,T){var V=U.sourceIndex-T.sourceIndex;if(V===0){hasDuplicate=true}return V}}else{if(document.createRange){G=function(W,U){var V=W.ownerDocument.createRange(),T=U.ownerDocument.createRange();V.selectNode(W);V.collapse(true);T.selectNode(U);T.collapse(true);var X=V.compareBoundaryPoints(Range.START_TO_END,T);if(X===0){hasDuplicate=true}return X}}}}(function(){var U=document.createElement("form"),V="script"+(new Date).getTime();U.innerHTML="<input name='"+V+"'/>";var T=document.documentElement;T.insertBefore(U,T.firstChild);if(!!document.getElementById(V)){I.find.ID=function(X,Y,Z){if(typeof Y.getElementById!=="undefined"&&!Z){var W=Y.getElementById(X[1]);return W?W.id===X[1]||typeof W.getAttributeNode!=="undefined"&&W.getAttributeNode("id").nodeValue===X[1]?[W]:g:[]}};I.filter.ID=function(Y,W){var X=typeof Y.getAttributeNode!=="undefined"&&Y.getAttributeNode("id");return Y.nodeType===1&&X&&X.nodeValue===W}}T.removeChild(U)})();(function(){var T=document.createElement("div");T.appendChild(document.createComment(""));if(T.getElementsByTagName("*").length>0){I.find.TAG=function(U,Y){var X=Y.getElementsByTagName(U[1]);if(U[1]==="*"){var W=[];for(var V=0;X[V];V++){if(X[V].nodeType===1){W.push(X[V])}}X=W}return X}}T.innerHTML="a<select><option>text</option></select><object><param/></object>';var H=K.getElementsByTagName("*"),E=K.getElementsByTagName("a")[0];if(!H||!H.length||!E){return}o.support={leadingWhitespace:K.firstChild.nodeType==3,tbody:!K.getElementsByTagName("tbody").length,objectAll:!!K.getElementsByTagName("object")[0].getElementsByTagName("*").length,htmlSerialize:!!K.getElementsByTagName("link").length,style:/red/.test(E.getAttribute("style")),hrefNormalized:E.getAttribute("href")==="/a",opacity:E.style.opacity==="0.5",cssFloat:!!E.style.cssFloat,scriptEval:false,noCloneEvent:true,boxModel:null};G.type="text/javascript";try{G.appendChild(document.createTextNode("window."+J+"=1;"))}catch(I){}F.insertBefore(G,F.firstChild);if(l[J]){o.support.scriptEval=true;delete l[J]}F.removeChild(G);if(K.attachEvent&&K.fireEvent){K.attachEvent("onclick",function(){o.support.noCloneEvent=false;K.detachEvent("onclick",arguments.callee)});K.cloneNode(true).fireEvent("onclick")}o(function(){var L=document.createElement("div");L.style.width=L.style.paddingLeft="1px";document.body.appendChild(L);o.boxModel=o.support.boxModel=L.offsetWidth===2;document.body.removeChild(L).style.display="none"})})();var w=o.support.cssFloat?"cssFloat":"styleFloat";o.props={"for":"htmlFor","class":"className","float":w,cssFloat:w,styleFloat:w,readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",tabindex:"tabIndex"};o.fn.extend({_load:o.fn.load,load:function(G,J,K){if(typeof G!=="string"){return this._load(G)}var I=G.indexOf(" ");if(I>=0){var E=G.slice(I,G.length);G=G.slice(0,I)}var H="GET";if(J){if(o.isFunction(J)){K=J;J=null}else{if(typeof J==="object"){J=o.param(J);H="POST"}}}var F=this;o.ajax({url:G,type:H,dataType:"html",data:J,complete:function(M,L){if(L=="success"||L=="notmodified"){F.html(E?o("<div/>").append(M.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(E):M.responseText)}if(K){F.each(K,[M.responseText,L,M])}}});return this},serialize:function(){return o.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?o.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password|search/i.test(this.type))}).map(function(E,F){var G=o(this).val();return G==null?null:o.isArray(G)?o.map(G,function(I,H){return{name:F.name,value:I}}):{name:F.name,value:G}}).get()}});o.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(E,F){o.fn[F]=function(G){return this.bind(F,G)}});var r=e();o.extend({get:function(E,G,H,F){if(o.isFunction(G)){H=G;G=null}return o.ajax({type:"GET",url:E,data:G,success:H,dataType:F})},getScript:function(E,F){return o.get(E,null,F,"script")},getJSON:function(E,F,G){return o.get(E,F,G,"json")},post:function(E,G,H,F){if(o.isFunction(G)){H=G;G={}}return o.ajax({type:"POST",url:E,data:G,success:H,dataType:F})},ajaxSetup:function(E){o.extend(o.ajaxSettings,E)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return l.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest()},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(M){M=o.extend(true,M,o.extend(true,{},o.ajaxSettings,M));var W,F=/=\?(&|$)/g,R,V,G=M.type.toUpperCase();if(M.data&&M.processData&&typeof M.data!=="string"){M.data=o.param(M.data)}if(M.dataType=="jsonp"){if(G=="GET"){if(!M.url.match(F)){M.url+=(M.url.match(/\?/)?"&":"?")+(M.jsonp||"callback")+"=?"}}else{if(!M.data||!M.data.match(F)){M.data=(M.data?M.data+"&":"")+(M.jsonp||"callback")+"=?"}}M.dataType="json"}if(M.dataType=="json"&&(M.data&&M.data.match(F)||M.url.match(F))){W="jsonp"+r++;if(M.data){M.data=(M.data+"").replace(F,"="+W+"$1")}M.url=M.url.replace(F,"="+W+"$1");M.dataType="script";l[W]=function(X){V=X;I();L();l[W]=g;try{delete l[W]}catch(Y){}if(H){H.removeChild(T)}}}if(M.dataType=="script"&&M.cache==null){M.cache=false}if(M.cache===false&&G=="GET"){var E=e();var U=M.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+E+"$2");M.url=U+((U==M.url)?(M.url.match(/\?/)?"&":"?")+"_="+E:"")}if(M.data&&G=="GET"){M.url+=(M.url.match(/\?/)?"&":"?")+M.data;M.data=null}if(M.global&&!o.active++){o.event.trigger("ajaxStart")}var Q=/^(\w+:)?\/\/([^\/?#]+)/.exec(M.url);if(M.dataType=="script"&&G=="GET"&&Q&&(Q[1]&&Q[1]!=location.protocol||Q[2]!=location.host)){var H=document.getElementsByTagName("head")[0];var T=document.createElement("script");T.src=M.url;if(M.scriptCharset){T.charset=M.scriptCharset}if(!W){var O=false;T.onload=T.onreadystatechange=function(){if(!O&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){O=true;I();L();T.onload=T.onreadystatechange=null;H.removeChild(T)}}}H.appendChild(T);return g}var K=false;var J=M.xhr();if(M.username){J.open(G,M.url,M.async,M.username,M.password)}else{J.open(G,M.url,M.async)}try{if(M.data){J.setRequestHeader("Content-Type",M.contentType)}if(M.ifModified){J.setRequestHeader("If-Modified-Since",o.lastModified[M.url]||"Thu, 01 Jan 1970 00:00:00 GMT")}J.setRequestHeader("X-Requested-With","XMLHttpRequest");J.setRequestHeader("Accept",M.dataType&&M.accepts[M.dataType]?M.accepts[M.dataType]+", */*":M.accepts._default)}catch(S){}if(M.beforeSend&&M.beforeSend(J,M)===false){if(M.global&&!--o.active){o.event.trigger("ajaxStop")}J.abort();return false}if(M.global){o.event.trigger("ajaxSend",[J,M])}var N=function(X){if(J.readyState==0){if(P){clearInterval(P);P=null;if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}}else{if(!K&&J&&(J.readyState==4||X=="timeout")){K=true;if(P){clearInterval(P);P=null}R=X=="timeout"?"timeout":!o.httpSuccess(J)?"error":M.ifModified&&o.httpNotModified(J,M.url)?"notmodified":"success";if(R=="success"){try{V=o.httpData(J,M.dataType,M)}catch(Z){R="parsererror"}}if(R=="success"){var Y;try{Y=J.getResponseHeader("Last-Modified")}catch(Z){}if(M.ifModified&&Y){o.lastModified[M.url]=Y}if(!W){I()}}else{o.handleError(M,J,R)}L();if(X){J.abort()}if(M.async){J=null}}}};if(M.async){var P=setInterval(N,13);if(M.timeout>0){setTimeout(function(){if(J&&!K){N("timeout")}},M.timeout)}}try{J.send(M.data)}catch(S){o.handleError(M,J,null,S)}if(!M.async){N()}function I(){if(M.success){M.success(V,R)}if(M.global){o.event.trigger("ajaxSuccess",[J,M])}}function L(){if(M.complete){M.complete(J,R)}if(M.global){o.event.trigger("ajaxComplete",[J,M])}if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}return J},handleError:function(F,H,E,G){if(F.error){F.error(H,E,G)}if(F.global){o.event.trigger("ajaxError",[H,F,G])}},active:0,httpSuccess:function(F){try{return !F.status&&location.protocol=="file:"||(F.status>=200&&F.status<300)||F.status==304||F.status==1223}catch(E){}return false},httpNotModified:function(G,E){try{var H=G.getResponseHeader("Last-Modified");return G.status==304||H==o.lastModified[E]}catch(F){}return false},httpData:function(J,H,G){var F=J.getResponseHeader("content-type"),E=H=="xml"||!H&&F&&F.indexOf("xml")>=0,I=E?J.responseXML:J.responseText;if(E&&I.documentElement.tagName=="parsererror"){throw"parsererror"}if(G&&G.dataFilter){I=G.d
You want to add
evt.preventDefault();
evt.stopPropogation()
to your function attached to the click.
I don't see where .setForm is coming from either so you data is probably undefined.
Any reason you are using live? It's not necessary if the HTML is already there when the page loads.
Anyhow, the proper way to stop the form submission if you are using AJAX is not to catch the button's click event, but the form's submit event. You can then cancel the form's default action and do your AJAX stuff. This is best for usability.
This would be appropriate for the HTML above:
$(function() {
$('#form').submit(function() {
$.ajax({
data: $(this).serialize(),
url: $(this).attr('action'),
type: $(this).attr('method'),
success: function(r) {
//...
}
});
return false; // prevent form from submitting
});
});
Related
Only slideUp the deleted message
I'm using a PM system and added the delete-message feature. I've got a form which checks for the message_id and message_title. The form posts to delete_message.php page which contains the query to delete the message. This has been done via Javascript as I dont want the page to refresh. I've got two functions for this: function deleteMessage() { $.ajax({ url: "message/delete_message.php", type: "POST", data: $("#delMsgForm").serialize(), success: function(data,textStatus,jqXHR){ finishDeleteMessage(data,textStatus,jqXHR); } }); } function finishDeleteMessage( data , textStatus ,jqXHR ) { $(".inboxMessage").slideUp('slow'); } Currently when I click on the delete button (image of a trashcan) it deletes the message without reloading the page, as a finishing touch, it slidesUp the divclass (inboxMessage) the message is in. Since I tell it to slide up this class, it slides up every message. This is my piece of code containing the classes and the form: <div class="inboxMessage"> <div class="inboxMessageImg NoNewMsg"></div> <div class="inboxMessageHeader"> <a id="ajax" class="inboxMessageLink" onclick="showMessage('.$row['message_id'].')">'.$row['message_title'].'</a> <p class="inboxMessageStatus Read">'.$inboxMessageStatus_Read.'</p> </div> <div class="inboxMessageDescription">'.$inboxMessageDescription.'</div> <div class="inboxMessageActions"> <form id="delMsgForm" name="delMsgForm" action="message/delete_message.php" method="post"> <input type="hidden" id="msgTitle" value="'.$row['message_title'].'" name="message_title"> <input type="hidden" id="msgID" value="'.$row['message_id'].'" name="message_id"> </form> <input type="submit" id="ajax" value="" name="deleteMessageButton" class="deleteMessageIcon" onclick="deleteMessage()"> </div> </div> What I want it to do is to slideUp only the message which has just been deleted by the user. I know this has to be done by telling javascript to only slideUp the deleted message which contains the message_id and/or message_title. I've tried several things, but no love whatsoever. I'm also not that familiar with javascript/ajax. Any help would be highly appreciate. Cheers :)
where do you call deleteMessage from? indirect the function call through another function which knows the parent of your "trash can", and can call slide up on that specific one. function deleteMessage (element) { //element will be clicked button var container = $(element).closest("div.inboxMessage"), //container div including the trashcan $.ajax({ url: "message/delete_message.php", type: "POST", data: $("#delMsgForm").serialize(), success: function(data,textStatus,jqXHR){ finishDeleteMessage(container); } }); }); and this will be your button <input type="submit" id="ajax" value="" name="deleteMessageButton" class="deleteMessageIcon" onclick="deleteMessage(this)">
Apparently, you've got more divs with class inboxMessage. Since you're adding this code: $(".inboxMessage").slideUp('slow'); .. all divs with that class will remove. If you want just one div to remove, give it a unique ID or data-attribute and hide it that way. For example: add the message-id to the div.. <div class="inboxMessage" id="(message_id)"> ..and use.. $(".inboxMessage#message_id").slideUp('slow'); .. to slide up the right div. Edit: Add your message ID to the div and to the function deleteMessage(), so it will be deleteMessage(message_id). function deleteMessage(message_id) { $.ajax({ url: "message/delete_message.php", type: "POST", data: $("#delMsgForm").serialize(), success: function(){ finishDeleteMessage(message_id); } }); } function finishDeleteMessage(message_id) { $(".inboxMessage#"+message_id).slideUp('slow'); }
How can I remove AutoNumeric formatting before submitting form?
I'm using the jQuery plugin AutoNumeric but when I submit a form, I can't remove the formatting on the fields before POST. I tried to use $('input').autonumeric('destroy') (and other methods) but it leaves the formatting on the text fields. How can I POST the unformatted data to the server? How can I remove the formatting? Is there an attribute for it in the initial config, or somewhere else? I don't want to send the serialized form data to the server (with AJAX). I want to submit the form with the unformatted data like a normal HTML action.
I wrote a better, somewhat more general hack for this in jQuery $('form').submit(function(){ var form = $(this); $('input').each(function(i){ var self = $(this); try{ var v = self.autoNumeric('get'); self.autoNumeric('destroy'); self.val(v); }catch(err){ console.log("Not an autonumeric field: " + self.attr("name")); } }); return true; }); This code cleans form w/ error handling on not autoNumeric values.
With newer versions you can use the option: unformatOnSubmit: true
Inside data callback you must call getString method like below: $("#form").autosave({ callbacks: { data: function (options, $inputs, formData) { return $("#form").autoNumeric("getString"); }, trigger: { method: "interval", options: { interval: 300000 } }, save: { method: "ajax", options: { type: "POST", url: '/Action', success: function (data) { } } } } });
Use the get method. 'get' | returns un-formatted object via ".val()" or ".text()" | $(selector).autoNumeric('get'); <script type="text/javascript"> function clean(form) { form["my_field"].value = "15"; } </script> <form method="post" action="submit.php" onsubmit="clean(this)"> <input type="text" name="my_field"> </form> This will always submit "15". Now get creative :) Mirrored raw value: <form method="post" action="submit.php"> <input type="text" name="my_field_formatted" id="my_field_formatted"> <input type="hidden" name="my_field" id="my_field_raw"> </form> <script type="text/javascript"> $("#my_field_formatted").change(function () { $("#my_field").val($("#my_field_formatted").autoNumeric("get")); }); </script> The in submit.php ignore the value for my_field_formatted and use my_field instead.
You can always use php str_replace function str_repalce(',','',$stringYouWantToFix); it will remove all commas. you can cast the value to integer if necessary.
$("input.classname").autoNumeric('init',{your_options}); $('form').submit(function(){ var form=$(this); $('form').find('input.classname').each(function(){ var self=$(this); var v = self.autoNumeric('get'); // self.autoNumeric('destroy'); self.val(v); }); }); classname is your input class that will init as autoNumeric Sorry for bad English ^_^
There is another solution for integration which doesn't interfere with your client-side validation nor causes the flash of unformatted text before submission: var input = $(selector); var proxy = document.createElement('input'); proxy.type = 'text'; input.parent().prepend(proxy); proxy = $(proxy); proxy.autoNumeric('init', options); proxy.autoNumeric('set', input.val())'' proxy.change(function () { input.val(proxy.autoNumeric('get')); });
You could use the getArray method (http://www.decorplanit.com/plugin/#getArrayAnchor). $.post("myScript.php", $('#mainFormData').autoNumeric('getArray'));
I came up with this, seems like the cleanest way. I know it's a pretty old thread but it's the first Google match, so i'll leave it here for future $('form').on('submit', function(){ $('.curr').each(function(){ $(this).autoNumeric('update', {aSign: '', aDec: '.', aSep: ''});; }); });
Solution for AJAX Use Case I believe this is better answer among all of those mentioned above, as the person who wrote the question is doing AJAX. So kindly upvote it, so that people find it easily. For non-ajax form submission, answer given by #jpaoletti is the right one. // Get a reference to any one of the AutoNumeric element on the form to be submitted var element = AutoNumeric.getAutoNumericElement('#modifyQuantity'); // Unformat ALL elements belonging to the form that includes above element // Note: Do not perform following in AJAX beforeSend event, it will not work element.formUnformat(); $.ajax({ url: "<url>", data : { ids : ids, orderType : $('#modifyOrderType').val(), // Directly use val() for all AutoNumeric fields (they will be unformatted now) quantity : $('#modifyQuantity').val(), price : $('#modifyPrice').val(), triggerPrice : $('#modifyTriggerPrice').val() } }) .always(function( ) { // When AJAX is finished, re-apply formatting element.formReformat(); });
autoNumeric("getArray") no longer works. unformatOnSubmit: true does not seem to work when form is submitted with Ajax using serializeArray(). Instead use formArrayFormatted to get the equivalent serialised data of form.serializeArray() Just get any AutoNumeric initialised element from the form and call the method. It will serialise the entire form including non-autonumeric inputs. $.ajax({ type: "POST", url: url, data: AutoNumeric.getAutoNumericElement("#anyElement").formArrayFormatted(), )};
Passing in a global javascript array to jQuery document(ready)
I have the following html rendered from templating (jsRender) <div class="noteActions top" style="z-index: 3;"> <span onclick="noteAction('add', 13808, 0 );"></span> <span onclick="noteAction('update',13808, 106344 );"></span> <span onclick="noteAction('delete', 13808, 106344 );"></span> </div> My issue is I have a function outside the document ready that is setting a data array that later, a jquery dialog window submits via ajax to the handler to update the database What's happening is the data array correctly passes everything except the jquery vals by class selector (pr-body, pr-title), they pass as NULL javascript - outside document (ready) var updateUrl = 'handlers/Poster.ashx', data; function noteAction(action, prospectID, noteID){ data = { 'operation': action, 'prospectid':prospectID, 'note-body' : $('.pr-body').val(), 'note-title' : $('.pr-title').val(), 'note-id':noteID, }; if (action == 'add'){ $( "#dialogPostIt" ).dialog("open", "option", "title", "Add Post It"); } else if (action == 'update'){ $( "#dialogPostIt" ).dialog("open", "option", "title", "Edit Post It"); } else if (action == 'delete'){ if (!confirm('Are you sure you want to delete')) return false; $.post(updateUrl+"?operation=delete¬eid="+noteID, function(data) { $('#stickyNote-'+noteID).remove(); }); } } jquery - document ready $(document).ready(function() { $( "#dialogPostIt" ).dialog({autoOpen: false, modal:true, buttons: { 'Save': function() { $.ajax({ url: updateUrl, data: data, success: function(json, textStatus, jqXHR){ ..... html <div id="dialogPostIt" > <form id="postItNow" action="" method="post" class="note-form"> <label for="note-title">Title (description)</label> <input type="text" name="note-title" id="note-title" class="pr-title" value="" /> <label for="note-body">Text of the note</label> <textarea name="note-body" id="note-body" class="pr-body" cols="30" rows="6"> </textarea> </form></div> I previously was setting the data array inside the dialog save button function(), which worked fine, but I needed to make some of the array elements dynamic based on event The array doesnt have to be global from my requirements, i just couldnt think of another way todo this As Always, any help is greatly appreciated
Well, i feel like a real dope, it actually is working fine, issue was pilot error -_- The data array was returning the values correctly, problem is there was no values yet , as the data was set prior to the subsequent dialog containing the form, so no form vals couldve been filled in yet the fix javascript outside the document ready function noteAction(action, prospectID, noteID){ data = { 'operation': action, 'prospectid':prospectID, 'notebody' : '', 'notetitle' : '', 'noteid':noteID, }; jquery in dialog (document ready) $( "#dialogPostIt" ).dialog({autoOpen: false, modal:true, buttons: { 'Save': function() { data.notebody = $('.pr-body').val(); data.notetitle= $('.pr-title').val(), $.ajax({ url: updateUrl, data: data,
after success function div value back to first value
<div id="user">username1</div> <script language="javascript"> $('.button').live('click',function(){ $("#user").html('<img src="loading.gif">'); $.ajax({ type: "POST", url: "getuserid.php", data: "userid="+userid, success: function(html){ $("#user").append(html); alert(html); } }); }); </script> i have several button with button class after i click button with .button class i see appended data to #user (returned from server) but after click alerted message, data in "#user" backed to first value "username1". why? if i remove alert(html) i cant see appended data at all.
We can only guess because you didn't provide much code, but presumably your .button element is an actual HTML <button /> (or worse, an <input type="button" />) and it's probably leading to your page being refreshed. Use preventDefault to stop this behaviour: $('.button').live('click',function(e){ $("#user").html('<img src="loading.gif">'); $.ajax(.....); e.preventDefault(); });
Where is the problem in this prototype [ajax.Request] code?
function sendM() { new Ajax.Request("sendm.html", { method: 'post', postBody: 'text='+ $F('text') +'&sub='+ $F('subject') +'&sname='+ $F('name') +'&sfmail='+ $F('email') +'to='+ $F('to'), onLoading:showLoad, onComplete: showResponse }); } function showLoad(){ $('dresult').innerHTML= "מבצע את הפעולה <br /><br />"; } function showResponse(req){ $('dresult').innerHTML= req.responseText; } The hTML Form code : <form id="sfunc" name="sfunc" onsubmit="return false;"> שם דוא"ל יעד 1 2 3 נושא הודעה
You attempted to use showLoad and showResponse before they were initialized. Move your function definitions for showLoad and showResponse above your Ajax request. For future reference, note that any error occuring inside your Ajax handlers do not print out errors in your browser error console. You'll have to create breakpoints in the handlers to fix the problem. Use a debugger like Firefox's Firebug plugin.