Safari has trouble with AJAX cross-origin requests, while Chrome and Firefox handle them without issue

I am developing a Shopify app that utilizes script tags and requires an ajax call to our server to retrieve necessary information about the shop. While everything seemed to be functioning correctly, my colleague pointed out that it was not working on his iPhone. Additionally, it is not working in Safari on Mac, although it works fine in Chrome.

Upon further investigation, I noticed that the status of the request is always "0" in Safari. When attempting a request to the test shop instead of our server, I received a 200 status, leading me to believe that this issue is related to cross-origin problems.

After exploring possible solutions, I have tried adjusting the headers on the requested page. Despite already including "Access-Control-Allow-Origin: *" and testing various suggestions, nothing seems to resolve the issue.

This is the current setup on the requested page using Laravel:

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");

$shop = Shop::where("domain", request('shop'))->first();

echo json_encode(
[ 
    'logo' => $shop->logo, 
    'text' => $shop->customizable_text, 
    'version' => $shop['plan'] 
]);

And here is the JavaScript function currently being used to make the call (originally using jQuery but switched to plain JavaScript for troubleshooting):

function ajaxRequest(url, parameters, callback){
const req = new XMLHttpRequest();

req.onreadystatechange = function(event) {
    // XMLHttpRequest.DONE === 4
    if (this.readyState === XMLHttpRequest.DONE) {
        if (this.status === 200) {
            callback(this.responseText);
        } else {
            console.log("Status: %d (%s)", this.status, this.statusText);
        }
    }
};

if(parameters.keys.length){
    url = url + "?"
    for(var i = 0; i < parameters.param.length; i++){
        if(i == 0){
            url = url + parameters.keys[i] + "=" + parameters.param[i]
        }
        else{
            url = url + "&" + parameters.keys[i] + "=" + parameters.param[i];
        }
    }
}

req.open('GET', url, true);
req.send(null);
}

While the functionality is as expected in Chrome and Firefox, there are issues specifically with Safari. Any insights on how to address this problem would be greatly appreciated.

Answer №1

Make sure to enable all headers when testing to see if any are missing.

Access-Control-Allow-Headers: *

Answer №2

Once again, I made a foolish error by forgetting to add the 's' in 'https'. Safari refuses to send the request if an https website attempts to make a request to an http URL.

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

The functionality of reordering columns, virtual scrolling, and resizing the grid in jqgrid are not functioning properly

Implementing jqgrid with Symfony to display a datagrid has been a challenging task for me. Thanks to Oleg's insightful response, many of the major issues have been resolved. Below is a snippet of my code: <link rel="stylesheet" type="text/css" ...

What is the method for altering the color of specific columns?

I am currently testing out my Amchart with this example. Check out the working demo on code pen My goal is to modify the color of the first four columns. While I am aware that colors can be changed by specifying them in the JSON file as a property calle ...

Using jquery to loop through JSON objects based on their values

Looking to display the NBA Western Conference leaders by seed, I have utilized the JSON file available at: http://data.nba.com/data/v2014/json/mobile_teams/nba/2014/00_standings.json Here is the current setup: $(document).ready(function() { $.getJSON( ...

Limit the number input to only allow values between 0 and 100

I am utilizing the Number input component from MUI, which includes Increment and Decrement buttons for adjusting numbers. Is there a method to limit the input to only accept values ranging from 0 to 100 ? Additionally, how can I decrease the width of the ...

Updating an if statement in Rails views via AJAX: the ultimate guide

In my app, I have votable posts that users can vote on through AJAX. While this functionality works well, I also want to update the status of a post (indicating whether it is an agreed milestone) when a user votes through AJAX. Below is the code snippet fo ...

Some PDF files appear as blank when shown using a Base64 encoded string

I am attempting to display a PDF file on a web page using its base64 encoding. Below is the ReactJS code I am using: <object style={{ width: '100%', height:'842pt' }} type="application/pdf" data={`data:application/pdf;base ...

The Query.formatError message indicates that there is an issue with the 'users.email' column in the where clause of the database query

I'm having some trouble with a piece of code. Here's my signup function : exports.signup = (req, res) => { // Adding User to Database console.log("Processing func -> SignUp"); User.create({ name: req.body.name, username: req.body. ...

Retrieving user input in React by utilizing the onChange event handler

I have been tasked with creating a Quiz App and I am currently working on building it. The app consists of several components such as "question", "question-list", and "add-question". Within the "add-question" component, there is a form that allows users ...

retrieve file through an ajax call

When I click on a button, I want to send an AJAX download request. I attempted it like this: Here is my JavaScript code: var xhr = new XMLHttpRequest(); xhr.open("GET", "download.php"); xhr.send(); In the download.php file: <? header("Cache-Control: ...

Tips for eliminating duplicate values from an array

In my NodeJS code, I am currently comparing values in an array. The issue at hand is: I start with an empty array: var items = []; then proceed to insert some values into it: items[0] = {a:1, b:222}; items[1] = {a:1, b:333}; items[2] = {a:1, b:222}; ...

What is preventing me from updating one dropdown list based on the selection made in another dropdown list?

I have a situation on a classic asp page where there are two dropdown lists: <select id="ddlState" name="ddlState" runat="server"> <option value="KY">Kentucky</option> <option value="IN" ...

The TypeScript type 'Record<string, string>' cannot be directly assigned to a type of 'string'

I can't seem to figure out why this code isn't working. I've encountered similar issues in the past and never found a solution. The snippet goes like this: type dataType = { [key: string]: string | Record<string, string>; ...

Can we retrieve the CSS of an element?

Using Selenium's webdriverJS, I have automated tasks on an HTML5 page. To incorporate a CSS selector into a function, I had to rely on XPath for selecting elements: var complexXpath = "//*/div/a"; /* This is just an example */ var element = mydri ...

Troubleshooting issue with the JQuery .change function not working in HTML <select>

I can't figure out why this code isn't working. It seems like it should be simple enough. Take a look at my drop-down menu code: <div> <form> <select id='yearDropdown'> <c:forEach var="year ...

When a function is transferred from a parent component to a child component's Input() property, losing context is a common issue

I have encountered an issue while passing a function from the parent component to the child component's Input() property. The problem arises when the parent's function is called within the child component, causing the this keyword to refer to th ...

Magento: Retrieve all new information on cart items from AJAX response

My shopping cart is displaying a popup window with the following details: I am using AJAX calls to update multiple configurable items in the cart, each with custom options simultaneously. However, I am facing an issue where I only receive data for the fi ...

Issues concerning date and time manipulation - Library Moment.js

As a beginner in JavaScript, I've been working on an activity that generates a table of train times based on user input. However, I'm facing issues with formatting the arrival time correctly. Whenever I input the arrival time in military format ( ...

An uncaught security error occurred when attempting to execute the 'pushState' function on the 'History' object

Here are the routes in my application: const routes:Routes =[ {path:'', component:WelcomeComponent}, {path:'profile', component: ProfileComponent}, {path:'addcourse', component: AddcourseComponent}, {path:'course ...

What is the Most Effective Way to Arrange an Array of Objects Based on Property or Method?

Looking for ways to enhance my array sorting function, which currently sorts by property or method value. The existing code is functional, but I believe there's room for improvement due to redundant sections. optimizeSort(array: any, field: string): ...

You are only able to click the button once per day

I am working on a button that contains numeric values and updates a total number displayed on the page when clicked. I would like this button to only be clickable once per day, so that users cannot click it multiple times within a 24 hour period. Below i ...