To reduce duplicated script, I created the following plugin, and it works as long as data is left as is.
$.fn.myValid = function(rules, options) {
this.validate({
rules: rules.rules,
messages: rules.messages,
submitHandler: function(form) {
var o = Object.assign({},{
type:'POST',
url:null,
data: $(form).serializeArray(),
dataType: 'json',
success: function (rsp){
//Instead of reloading page, do dynamicly
$.unblockUI();
alert('record submitted')
location.reload();
},
error: function (xhr) {
$.unblockUI();
alert(xhr.responseJSON.message);
}
}, options);
//if (typeof o.data === "function") o.data=o.data(form);
$.blockUI();
$.ajax(o);
}
});
};
If data needs to be changed, I cannot simply return something like $(form).serializeArray().concat($('#common-inputs').serializeArray(form)) because form is not yet defined, so instead I thought returning a function would work. When ajax is fired, however, data is a function, and not a string, array, or plain object, so data is not sent to the server.
$('#help-form').myValid(validObj.common, {url:'ajax.php','data': function(form){
console.log('this is never executed);
return $(form).serializeArray().concat($('#common-inputs').serializeArray(form))
}});
As a workaround, I included o.data=o.data(form); (is commented out in above script) to execute the function to return results, and it works as desired. I expect, however, it is more of a hack, and there is a correct way to do this.
What is the proper way to use a function as data with jQuery ajax?
Will the solution be different for other properties such as url, success, etc?
applyfunction. I have a github with the wrapper, It's a little outdated but I think you can see the ideea. Maybe you can apply the logic to your plugin github.com/sabbin/JQPS-Framework