I am trying to call my ajax code after my js validate() methods returns true on submit of the searchId button. But the ajax code is not executing. if I place an alert there it works fine. Where I am doing wrong? Please help!!
here is my javascript code
<script language="JavaScript">
function validate()
{
var msg = "";
//all my field validations are here
msg += "o Name is not a valid name.\n";
if (msg > "") {
alert(msg);
return false;
}
else {
return true;
}
}
$(document).ready(function(){
$("#simple-post").click(function()
{
$("#ajaxform").submit(function(e)
{
// getting the values of both firstname and lastname
var beginDate = $('input[name="txtBeginDate"]').val();
var endDate = $('input[name="txtEndDate"]').val();
var mdnVal = $('input[name="txtMsid"]').val();
// posting the values
var dataString = 'beginDate=' + beginDate + '&endDate=' + endDate+ '&mdnVal=' + mdnVal;
alert(dataString);
var formURL = $(this).attr("action");
//alert(formURL);
$.ajax(
{
url : formURL,
dataType:'json',
async: false,
data: dataString,
beforeSubmit: validate,
success:function(data){
queryObject = eval('(' + JSON.stringify(data) + ')');
queryObjectLen = queryObject.empdetails.length;
drawChart();
},
error : function(xhr, type) {
alert('server error occoured')
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
$("#ajaxform").submit(); //Submit the FORM
});
});
Here is my HTML code
<form name="ajaxform" id="ajaxform" action="getData.jsp" onSubmit="return validate();" method="POST">
<Table>
<input type="submit" name="action" value="Search" id="searchId">
<input type="text" name="name" id="id" size="10" maxlength="10">
//other input fields
</table>
</form>
<button class="btn btn-info" id="simple-post">Run Code</button>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
UPDATE
I have updated my code, i can submit my form, but the validation not working. I am using beforeSubmit: validate, still i dont see my validation messages. Please help.
I fxed the problem. Added a Submit button markup and removed Run Code. Changed onsubmit to onclick on the submit button. Again removed $("#simple-post").click(function() form my jquery code.This seems to be working fine now.
Thanks to this post
Validate a form with javascript before submitting with ajax?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.