Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

formData get() Doesn't seem to work in Safari

Tags:

safari

This is my code. It works in Firefox and Chrome but not Safari. I get no errors.

<script>
var cleanData = new FormData();
cleanData.append("test", "test");
alert(cleanData.get("test"));
</script>

Does anyone know a workaround?

like image 766
Michael Coyne Avatar asked Aug 11 '16 13:08

Michael Coyne


2 Answers

Apparently, Safari has no means of getting values stored in FormData objects at this time. There is no workaround at this time, and apparently it's not practical to polyfill.

Sorry :(

Notes: https://developer.mozilla.org/en-US/docs/Web/API/FormData/get#Browser_compatibility https://www.bountysource.com/issues/27573236-is-it-possible-to-polyfill-missing-formdata-methods

like image 116
Benjamin Avatar answered Oct 14 '22 16:10

Benjamin


I solved this by conditionally (if Safari is the browser) iterating through the elements property of an actual form. For all other browser, my wrapper just iterates through FormData entries(). The end result of my function, in either case, is a simple javascript object (JSON) which amounts to name/value pairs.

function FormDataNameValuePairs(FormName)
{
  var FormDaytaObject={};
  var FormElement=$('#'+FormName).get(0);

  if (IsSafariBrowser())
  {
    var FormElementCollection=FormElement.elements;
    //console.log('namedItem='+FormElementCollection.namedItem('KEY'));
    var JQEle,EleType;
    for (ele=0; (ele < FormElementCollection.length); ele++)
    {
      JQEle=$(FormElementCollection.item(ele));
      EleType=JQEle.attr('type');

      // https://github.com/jimmywarting/FormData/blob/master/FormData.js
      if ((! JQEle.attr('name')) ||
          (((EleType == 'checkbox') || (EleType == 'radio')) &&
           (! JQEle.prop('checked'))))
        continue;
      FormDaytaObject[JQEle.attr('name')]=JQEle.val();
    }
  }
  else
  {
    var FormDayta=new FormData(FormElement);
    for (var fld of FormDayta.entries())
      FormDaytaObject[fld[0]]=fld[1];
  }

  return FormDaytaObject;
}

where IsSafariBrowser() is implemented by whatever your favorite method is, but I chose this:

function IsSafariBrowser()
{
  var VendorName=window.navigator.vendor;
  return ((VendorName.indexOf('Apple') > -1) &&
          (window.navigator.userAgent.indexOf('Safari') > -1));
}

Example usage in OP's case, assuming that you have an actual form called CleanDataForm instead of creating a FormData from scratch:

var cleanData=FormDataNameValuePairs('CleanDataForm');
alert(cleanData.test);
like image 28
bitshftr Avatar answered Oct 14 '22 15:10

bitshftr