I have an ajax submit that wouldn’t run no matter what I tried. That is until I found a tutorial that had the submit wrapped in a $(function () {}); call. I then wrapped my .submit in a function call and it seemed to have worked. The thing that boggles my mind is that I have other .submit ajax function calls that work just as well without being wrapped in a function. I am wondering if I am missing a jQuery nuance here that I don’t understand?
To more fully illustrate what I mean, here is my function before and after I wrap it in a function…
Before…
$("#FormPutMsg1").submit(function (e) {
debugger;
e.preventDefault();
//animateSpinner();
var theURL = this.action;
var type = "POST";//this.methd;
var data = $(this).serialize();
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
dataType: "json",
success: function (result) {
debugger;
var data = result;
if (data.split(':')[0] == "Error") {
//$("#list").unblock();
$('#resultDiv').html('<b><p style="color: #ff00ff">' + data + '</p></b>');
setTimeout(function () {
$('#resultDiv').html("");
}, 10000);
}
else {
binddata(data);
}
}
});
return false;
});
After (this one works)…
$(function () {
$("#FormPutMsg1").submit(function (e) {
debugger;
e.preventDefault();
//animateSpinner();
var theURL = this.action;
var type = "POST";//this.methd;
var data = $(this).serialize();
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
dataType: "json",
success: function (result) {
debugger;
var data = result;
if (data.split(':')[0] == "Error") {
//$("#list").unblock();
$('#resultDiv').html('<b><p style="color: #ff00ff">' + data + '</p></b>');
setTimeout(function () {
$('#resultDiv').html("");
}, 10000);
}
else {
binddata(data);
}
}
});
return false;
});
});
Before I wrapped my function in a function the regular submit functionality prevaled (because e.preventDefault was never called I presume). Am I missing something gentlemen (and ladies)?
The original code block will never got executed because “#FormPutMsg1” wont yet exist. The second code block is executed after the page has been loaded so “#FormPutMsg1” would exist.
$(“#FormPutMsg1”).submit() requires a trigger for it be executed. Wrapping it with “$(function() {})” will execute the block on page load. You could also trigger it using a click’ event.
“$(function() {})” is a shortcut for “$(document).ready(function() {})”