To handle browser compatibility issues, I developed a function that dynamically adjusts based on whether the user is using Safari or another browser. If detecting Safari, the function iterates through the elements property of the form; for other browsers, it loops through FormData entries(). The outcome in either scenario is a straightforward JavaScript object containing name/value pairs, which can be directly passed to the data parameter of JQuery's ajax function, without specifying contentType and processData.
function GetFormDataNameValuePairs(FormID) {
var FormDataObject = {};
var FormElement = $('#' + FormID).get(0);
if (IsSafariBrowser()) {
var FormElementCollection = FormElement.elements;
var JQEle, EleType;
for (ele = 0; (ele < FormElementCollection.length); ele++) {
JQEle = $(FormElementCollection.item(ele));
EleType = JQEle.attr('type');
if ((!JQEle.attr('name')) || (((EleType == 'checkbox') || (EleType == 'radio')) && (!JQEle.prop('checked')))) continue;
FormDataObject[JQEle.attr('name')] = JQEle.val();
}
} else {
var FormDataInfo = new FormData(FormElement);
for (var field of FormDataInfo.entries())
FormDataObject[field[0]] = field[1];
}
return FormDataObject;
}
The IsSafariBrowser() function checks if the current browser is Safari by inspecting properties like window.navigator.vendor and window.navigator.userAgent.
function IsSafariBrowser() {
var VendorName = window.navigator.vendor;
return ((VendorName.indexOf('Apple') > -1) && (window.navigator.userAgent.indexOf('Safari') > -1));
}
Here is an example of using this function with an ajax call:
var FormDataObject = GetFormDataNameValuePairs('MyForm');
$.ajax({
url: 'SubmitFormData/',
method: 'POST',
data: FormDataObject,
dataType: 'text',
success: function(data) {
console.log('Form submission successful: ' + data);
},
error: function(Jqxhr, Status, Error) {
console.log('Error submitting form data: ' + Error);
}
});