Safari is throwing an error message stating that FormData.entries() is not a valid function

My ajax function for posting an image works perfectly in Chrome and Firefox, but Safari and iOS Safari are having issues with it.

To create and append the value, I am using this code:

var ajaxImage = new FormData();
ajaxImage.append('file-0', $('.some-file-input')[0].files[0]);

Later on, when I try to call this image using ajaxImage.entries() to initialize the iterator for the FormData object, I encounter a TypeError in Safari stating that entries is not a function.

Although I could perform validation before reaching this point as a workaround, I find this issue bothering me and would appreciate any insights or solutions that anyone could provide.

Thanks!

Answer №2

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);
    }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discover how to apply unique styles to specific HTML elements using their index values in jQuery

In the process of creating a party game similar to Tambola or Housie, I am faced with the challenge of automatically detecting and highlighting the numbers called out on each ticket in the game. For instance, if number 86 is announced, I aim to visually di ...

Tips on utilizing AJAX to interact with PrestaShop information

I'm looking to enhance my prestashop store by adding some interactivity. However, I need to retrieve product data from the database in order to do so. I've already searched through the prestashop documentation but haven't found any helpful i ...

Submitting a form from a non-AngularJS application to an AngularJS app requires URL rewriting

I am facing a challenge with my AngularJS search application. The search box is located on a standard HTML page that is not part of the AngularJS framework. Here is how the input field looks: <form accept-charset="UTF-8" name="search" id="search" act ...

Increase the touch drag threshold inside a UIButton to 5 pixels, instead of the default of 1 pixel

Within my storyboard, there is a sole UIButton that I have integrated with a Touch Drag Inside action called myTouchDragInsideAction. This action is activated when the button is dragged from within its confines (UIControlEventTouchDragInside). An issue ha ...

NinjaCharts feature for displaying data labels, annotations, and recognizing gestures for Tick Marks

Looking to enhance my Shinobi Charts with custom gesture recognizers Currently seeking examples on how to implement touch-up gestures for Tick Marks and chart annotations While the documentation covers interacting with data series, I specifically need gu ...

Loop through each current value in an ng-repeat directive and use it in an

I'm facing a simple issue that doesn't seem to have an easy fix. I have a ng-repeat set up like this <p ng-repeat="title in Menu.data[Menu.selected]"> {{ title }} </p> Now, I want to add an onclick event so I adjusted i ...

Using a custom TypeScript wrapper for Next.js GetServerSideProps

I developed a wrapper for the SSR function GetServerSideProps to minimize redundancy. However, I am facing challenges in correctly typing it with TypeScript. Here is the wrapper: type WithSessionType = <T extends {}>( callback: GetServerSideProps&l ...

How to integrate a new DOM element into a React Native app with the simple click of a button

Is it possible to add a <Text> element with the click of a button in react native? If so, how can this be achieved? Here is my current code: import React, { Component } from 'react' import { StyleSheet, Text, View, Button } from &apos ...

Is jQuery failing to serialize the form data?

I have a question regarding my form. When I try to serialize it using a jQuery script, the output is empty. Could someone please assist me with this issue? Here is a snippet of my form: <form id="tabb2"> <!-- *************************** ...

The framework 'FIRAnalyticsConnector.framework/FIRAnalyticsConnector' is being built for Mac Catalyst, specifically for architecture x86_64

While running my project on Mac with catalyst, I encountered an error related to Firebase. Please click here to access the pod file. An issue arose when building for Mac Catalyst and linking in an object file built for iOS Simulator. The error occurred i ...

rails: User cancels AJAX request by closing tab mid-process

As a beginner in Ruby on Rails, I have a question regarding AJAX calls. What happens if a user closes the tab or navigates away after the call has been sent? Will the AJAX call continue to process or will it stop due to lack of session? If it does stop, i ...

Receiving JSON output twice

I am currently working with CodeIgniter and facing an issue with my form fields, which are Employee_name, fromDate, and endDate. I am using AJAX to send this data without sharing the actual code. The problem arises when retrieving and displaying records fr ...

React Color Input: The input format should follow the pattern of "#rrggbb", with rr, gg, and bb being two-digit hexadecimal values

The code is functioning correctly and as expected. The background color of the squares changes when each input is modified, and the squares update once the button is pressed. During development, there was a moment when the warning mentioned appeared brief ...

Printing without sufficient paper will result in an incomplete printout

https://i.stack.imgur.com/jNlRr.jpg I am facing an issue with printing the last column "Potensi". The text in this column is not fully printed. How can I resolve this problem? I am using PHP. Thank you ...

Safari is encountering an issue with the value provided for the width/height attribute in the <svg> element, as it is not a recognized

When adjusting the size of an SVG based on antd breakpoints, I encountered errors like these. I am passing props to an SVG element: const { lg } = useBreakpoint(); const height= lg ? "8rem" : xs ? "3rem" : "5rem"; const width ...

What methods can be used to control the URL and back button in a web application designed similar to an inbox in Gmail?

Similar Question: Exploring AJAX Techniques in Github's Source Browser In my application, there are essentially 2 main pages: The main page displays a list of applications (similar to an inbox) The single application page is packed with various ...

Adjusting specific sections of a container in real-time

Fiddle: https://jsfiddle.net/1b81gv7q/ Sorry for the slightly cryptic title; I couldn't come up with a better way to phrase it. Imagine this scenario: there's a container with content that needs to be dynamically replaced. If I wanted to repla ...

Making a Zoom effect using p5.js

I have searched for a solution to this question multiple times, but none of the answers I came across seem to work for me. Currently, I am able to allow the user to scale an image with a simple scale(factor) call. However, now I am attempting to implement ...

Ways to transfer data from JavaScript to Wicket framework

My Javascript method executes business logic on the client side and returns a value. I now want to access this value in my Wicket page. What is the most effective approach for achieving this? P.S. I am currently using Wicket 7. ...

observing the pathway and modifying a variable within a directive's scope

A specialized directive has been crafted below, designed to generate a series of buttons relying on the data supplied to it. angular.module('btnbar.directive', ['messaging']). directive("btnBar", function(){ return { restrict: &a ...