jquery - JSP form still submitting even though JavaScript validation returning false -
i have jsp form "deletecont" , javascript file function "validatedelete". when click "delete contact" button "validatedelete" function called , alert "alertmessage" displayed. however, "contactmaint" servlet still called though false being returned. please can tell me going wrong?
<form name="deletecont" onsubmit="return validatedelete('${sessionscope.account}','${sessionscope.firstname}', '${sessionscope.lastname}')" action="contactmaint" method="post"> <input type="submit" value="delete contact" name="delcontact"> </form> function validatedelete(account, contactfirstname, contactlastname) { urlstrg = "http://localhost:8080/salespoliticalmapping/jcheckcontacts?account=" + account + "&firstname=" + contactfirstname + "&lastname=" + contactlastname; $.get(urlstrg, function (result, status) { if (result.length > 0) { var alertmessage = "can't delect contact:"; (var = 0; < result.length; i++) { alertmessage += result[i]; } alert(alertmessage); return false; } }); } i have amended code follows although i'm not entirely sure why:
function validatedelete(account, contactfirstname, contactlastname) { $.ajaxsetup({async: false}); urlstrg = "http://localhost:8080/salespoliticalmapping/jcheckcontacts?account=" + account + "&firstname=" + contactfirstname + "&lastname=" + contactlastname; var valid = true; var alertmessage = ""; $.get(urlstrg, function(result, status) { if (result.length > 0) { valid = false; alertmessage = "can't delect contact:"; (var = 0; < result.length; i++) { alertmessage += result[i]; } } }); if (valid===false) { alert(alertmessage); return false;} };
there 2 problems:
you're firing ajax request. ajax requests default asynchronous. after
$.get()called, code advances next line while asynchronous request runs in background in different thread. there's in case apparently nothing after$.get(), returns (implicitlytrue).you're returning callback function, not main function. callback function returns main function, not outside. need return main function.
one way return false , explicitly submit form on success.
function validatedelete(...) { var $form = $(this); $.get(..., function(...) { if (success) { $form.submit(); } }); return false; } another way making ajax request asynchronous passing { async: false } option 2nd argument of $.get().
function validatedelete(...) { var valid = false; $.get(..., { async: true }, function(...) { if (success) { valid = true; } }); return valid; } please note problem has nothing jsp. you'd still have had same problem when using same script in view technology, such php, asp, etc, , in plain html page. jsp in context of question merely html code generator , can better omitted question in future problems html+css+js/jquery.
Comments
Post a Comment