ajax - jquery .preventDefault() issue -
i want forms handled code:
//all form submissions should go through here. $(document).on('submit', 'form', function (x) { //x.preventdefault(); //commented out because it's not working $.ajax({ url: $(this + '#formdestination').val(), //formdestination hidden field, showing submit form type: 'post', datatype: 'json', data: $(this).serialize(), complete: function (xhr, status) { if (status === 'error' || !xhr.responsetext) { window.location = '/broken/?err=inconsolable%20onsubmit%20ajax%20error'; //i'd real error here, ideally } //end if else { loader($('#pagedestination').val()); //loader function animates page loads new content. //#pagedestination hidden field stores page should go when it's done. //yes, know formdestination , pagedestination handled form or backend. there reasons not matter here. } //end else } //end complete function }); return false; }); there couple of problems i'm having.
1.) when form submitted, calls function. doesn't call loader, or if does, it's overridden controller's redirect. need prevent generic submit when form submitted. .preventdefault() not working (see below).
2.) (far less important #1) if ajax craps out, i'd legit error. how?
on .preventdefault() - when try it, error:uncaught syntaxerror: unexpected identifier
thanks help.
the exception getting coming other place, visit fiddle: http://jsfiddle.net/dgrla/
it has code:
$(document).on('click', '.test', function (x) { x.preventdefault(); //commented out because it's not working $.ajax({ url: "test.php", //formdestination hidden field, showing submit form type: 'post', datatype: 'json', data: $(this).serialize(), complete: function (xhr, status) { console.log("hi"); } }).fail(function () { alert("error"); }); }); when click "clickme" element both console.log , alert.
use "success" callback instead of "complete" one, , use deferred .fail capture error, try this:
$(document).on('submit', 'form', function (x) { x.preventdefault(); //commented out because it's not working var url = $(this).attr("action"); $.ajax({ url: url , // use form action attribute instead of hidden field type: 'post', datatype: 'json', data: $(this).serialize(), success: function (data) { loader($('#pagedestination').val()); } }).fail(function (error) { // error has sorts of fun stuff }); // return false; dont return false, preventdefault enough }); ps: mention loader sends user different page, there reason submit form ajax if going redirect page anyway?
Comments
Post a Comment