Leveraging Server Response Codes Across Different Domains Using JavaScript

Before anything else, I must acknowledge the cross-domain issues that may arise with JavaScript. The fact that I am seeing both 404 and 200 response codes in my console has made me reconsider this possibility.

The scenario... I am currently developing a website prototype featuring a video player that has a variety of file options. I am trying to establish a logic that goes as follows: if this file is available, play it if it's not available, try another file if that file is available, play it if it's not available, try another file and so on...

Initially, I attempted to accomplish this using XMLHttpRequest(). However, I encountered difficulty in implementing if/else logic due to the need to specify the URL in .open(). Upon discovering jQuery's .ajax() function with error/success options, I saw a potential solution. It occurred to me that I could nest .ajax() within the error function. As a result, progress has been made but not without encountering Access-Control-Allow-Origin errors alongside valid 404/200 responses. Hence, my question is "How can I incorporate those 404/200 responses into my code?"

Regarding JavaScript (and please suggest a more effective approach)...

function getSermonVideo() {
    "use strict";
    const params = new URLSearchParams(document.location.search);
    const filename = params.get("filename");
    const site = params.get("site");
    let date = params.get("date");
    let shortdate = date.slice(2);
    shortdate = shortdate.replaceAll("-", "");
    const editedvideourl = "https://flcmedia.org/productvideo/";
    const editedaudiourl = "https://flcmedia.org/product/";
    let uneditedurl = "https://flcmedia.org/" + site + "/";
    jQuery.ajax({
        url:editedvideourl + filename + ".mp4",
        type:'HEAD',
        error: function() {
            jQuery.ajax({
                url:editedvideourl + filename + "_480.mp4",
                type:'HEAD',
                error: function() {
                    jQuery.ajax({
                        url:editedaudiourl + filename + ".mp3",
                        type:'HEAD',
                        error: function() {
                            jQuery.ajax({
                                url: uneditedurl + "MP4/" + date.slice(0, 4) + "/" + shortdate + "Video.mp4",
                                type:'HEAD',
                                error: function() {
                                    jQuery.ajax({
                                        url: uneditedurl + "MP3/" + date.slice(0, 4) + "/" + shortdate + "Audio.mp3",
                                        type:'HEAD',
                                        error: function() {
                                            //console.log("No file exists.");
                                        },
                                        success: function() {
                                            videoplayer.src = uneditedurl + "MP3/" + date.slice(0, 4) + "/" + shortdate + "Audio.mp3"
                                        }
                                    });
                                },
                                success: function() {
                                    videoplayer.src = uneditedurl + "MP4/" + date.slice(0, 4) + "/" + shortdate + "Video.mp4"
                                }
                            });
                        },
                        success: function() {
                            videoplayer.src = editedaudiourl + filename + ".mp3";
                        }
                    });
                },
                success: function() {
                    videoplayer.src = editedvideourl + filename + "_480.mp4";
                }
            });
        },
        success: function() {
            videoplayer.src = editedvideourl + filename + ".mp4";
        }
    });
}

Edge Developer's Tools - Console...

Access to XMLHttpRequest at 'https://flcmedia.org/productvideo/1214-GodsIncorruptibleWordSeed-01-HisWordIsMedicine.mp4' from origin 'https://anti-exe.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
    HEAD https://flcmedia.org/productvideo/1214-GodsIncorruptibleWordSeed-01-HisWordIsMedicine.mp4 net::ERR_FAILED 200 (OK)
Access to XMLHttpRequest at 'https://flcmedia.org/productvideo/1214-GodsIncorruptibleWordSeed-01-HisWordIsMedicine_480.mp4' from origin 'https://anti-exe.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
    HEAD https://flcmedia.org/productvideo/1214-GodsIncorruptibleWordSeed-01-HisWordIsMedicine_480.mp4 net::ERR_FAILED 404 (Not Found)
Access to XMLHttpRequest at 'https://flcmedia.org/product/1214-GodsIncorruptibleWordSeed-01-HisWordIsMedicine.mp3' from origin 'https://anti-exe.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
    HEAD https://flcmedia.org/product/1214-GodsIncorruptibleWordSeed-01-HisWordIsMedicine.mp3 net::ERR_FAILED 200 (OK)
Access to XMLHttpRequest at 'https://flcmedia.org/FLCSarasota/MP4/2017/171126Video.mp4' from origin 'https://anti-exe.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
    HEAD https://flcmedia.org/FLCSarasota/MP4/2017/171126Video.mp4 net::ERR_FAILED 200 (OK)
Access to XMLHttpRequest at 'https://flcmedia.org/FLCSarasota/MP3/2017/171126Audio.mp3' from origin 'https://anti-exe.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
    HEAD https://flcmedia.org/FLCSarasota/MP3/2017/171126Audio.mp3 net::ERR_FAILED 200 (OK)
Access to fetch at 'https://flcmedia.org/productvideo/1214-GodsIncorruptibleWordSeed-01-HisWordIsMedicine.mp4' from origin 'https://anti-exe.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
    GET https://flcmedia.org/productvideo/1214-GodsIncorruptibleWordSeed-01-HisWordIsMedicine.mp4 net::ERR_FAILED 200 (OK)

As evident from the responses, some files return 200 while others return 404. Utilizing this information will enable me to implement the desired if/else logic. Do you have any suggestions?

Answer №1

This solution didn't directly address the 200/404 logic, but it did achieve the intended outcome by trying different files in sequence (first one file, then another if the first fails, and so on).

const videoplayer = document.getElementById("videoplayer");
function getSermonVideo() {
    "use strict";
    const params = new URLSearchParams(document.location.search);
    const filename = params.get("filename");
    const site = params.get("site");
    const number = params.get("number");
    let date = params.get("date");
    let shortdate = date.slice(2);
    shortdate = shortdate.replaceAll("-", "");
    const editedvideourl = "https://flcmedia.org/productvideo/";
    const editedaudiourl = "https://flcmedia.org/product/";
    let uneditedurl = "https://flcmedia.org/" + site + "/";
    // default video file
    videoplayer.src = editedvideourl + filename + "_480.mp4";
    videoplayer.onerror = function () {
        console.log("Edited _480.mp4 not available.");
        videoplayer.src = editedvideourl + filename + ".mp4";
        videoplayer.onerror = function () {
            console.log("Edited .mp4 not available.");
            videoplayer.src = editedaudiourl + filename + ".mp3";
            videoplayer.onerror = function () {
                console.log("Edited .mp3 not available.");
                videoplayer.src = uneditedurl + "MP4/" + date.slice(0, 4) + "/" + shortdate + "Video.mp4";
                videoplayer.onerror = function () {
                    console.log("Unedited .mp4 not available.");
                    videoplayer.src = uneditedurl + "MP3/" + date.slice(0, 4) + "/" + shortdate + "Audio.mp3";
                    videoplayer.onerror = function () {
                        console.log("Unedited .mp3 not available.");
                    };
                };
            };
        };
    };
}

Although there may be more efficient methods, this one successfully accomplishes the task.

It could potentially be optimized with more modern code, as suggested by CBroe...

videoplayer.addEventListener("error", () => {
    videoplayer.src = editedaudiourl + filename + ".mp3";
});

However, I personally found nesting within .onerror callbacks to be more intuitive.

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

Merge array and object destructuring techniques

What is the correct way to remove a value from an array? const ?? = { text: ['some text'] }; ...

Obtaining Spotify API access token using JavaScript code on the front end

I've developed a web application that enables users to generate a list of songs by artists related to a selected artist. The goal is to link the user's Spotify account and create a playlist based on this generated song list, which requires obtain ...

Is it possible to identify a legitimate JSONP response?

My goal is to exchange data with a web service on a separate server that lacks CORS support. I am required to utilize JSONP for this purpose. The service mandates authentication, and when the user is in an SSO environment, they are seamlessly passed throug ...

Search for specific parameters in an array and retrieve them

I have been attempting to sift through an array of data retrieved from my API, but unfortunately, the data remains unfiltered. I suspect that it might be due to the way I implemented my method or perhaps my params are not being returned correctly. Below ar ...

Text box is not automatically filling up when selecting from dropdown menu

I am currently facing an issue with a dropdown box that offers three different selections. I want the Group ID associated with the selected group to automatically populate in the textbox below. How can I achieve this functionality? Whenever I make a selec ...

Designing a book-style layout using jQuery

I am currently working on a web application that needs to display its data in a book-like format. The structure of the data is as follows: Menu{ String menuName; List<String> subMenu; } To achieve this, I utilized jQuery to dynamically generate ...

The JavaScript function String.split() is generating an array filled with 20 empty strings

Attempting to replicate the functionality of jQuery's string-based HTML element determination, I employed a split function. However, rather than returning a list of values as intended, it produced an array containing twenty empty strings. console.l ...

Using Javascript's OnChange event to dynamically update data

Attempting to achieve a seemingly straightforward task, but encountering obstacles. The goal is to trigger a JavaScript onChange command and instantly update a radar chart when a numerical value in a form is altered. While the initial values are successful ...

Error: The 'replace' property of null cannot be read in select2

In my Node Express app, I am incorporating select2, and encountering an error when supplying an array as the data source with data: dataBase. The issue arises as Uncaught TypeError: Cannot read property 'replace' of null. Although using an ajax ...

What is the best way to conditionally wrap a useState variable in an if statement without losing its value when accessing it outside the if block in reactjs?

I am facing a coding challenge with my cards state variable in React using the useState hook. I tried adding my array data to it but ended up with an empty array. Placing the state inside an if statement resulted in undefined variables. I attempted various ...

What is the best way to alter the color of faces in three.js?

I'm currently working with a sample script that involves flying bird objects. However, I am struggling to figure out how to change the color of the birds. I attempted to modify the color on the line where the birds are instantiated: bird = birds[i] ...

Out of nowhere, JavaScript/jQuery ceased to function

Everything was running smoothly on my website with jQuery Ui until I changed the color, and suddenly everything stopped working. Any ideas why this happened? I even tried writing the JavaScript within the HTML file and linking it as a separate .js file, bu ...

Incorporate an onclick event to the elements within the array

I'm currently working on iterating over an array and adding an onclick event to each element. My goal is to be able to click on each div and have them log their values in the console. However, I am facing a challenge in applying the onclick event to e ...

Discover the myriad of possibilities created by combining arrays

I am working on a code snippet that aims to generate an array containing all possible combinations between two or more arrays. However, I am encountering a specific issue. getCombn(arr: string | any[], pre?: string | undefined) { pre = pre || ' &a ...

Updating materials within the Forge

Currently, we have implemented a system where the client retrieves object states when the page loads, changing the colors of 'pending' objects in the model. We continue to poll for changes to update the coloring - initially coloring pending objec ...

Problem with Snowpack's internal module import paths

While working on a project, I am using npx snowpack build --watch instead of the dev command because of a Flask backend. However, I am facing issues with internal imports, specifically modules importing dependencies like Bootstrap importing Popper. The pr ...

What is the most foolproof method for detecting when a checkbox has been marked as checked, regardless of the circumstances?

Is there a way to detect changes in the checked value of a checkbox when it is changed by a script that I do not control? I have tried using `addEventListener()` and jQuery's `on()` method, but they do not work in all cases. <input type="checkbox" ...

Troubleshooting: Issues with the functionality of ng-include in AngularJS

Hi there, I am new to angular js and I'm attempting to integrate a simple html file into my page. Below is the code I am using: <!DOCTYPE html> <html ng-app=""> <head> </head> <body ng-controller="userController"> < ...

Angular JS Retrieving Data in the Background with the Assistance of $timeout or $interval Service

Looking to fetch data from a webapi in the background using either the $timeout or $interval service in Angular JS. I have some concerns about how the $timeout and $interval services work. I've run into issues when incorporating these services into m ...

What is the proper way to handle a 504 response header in an AJAX request using jQuery?

Recently, I encountered an issue with an AJAX call from the client that caught my attention. Here is a snapshot of how it looked: $.ajax({ 'url': '/converter/ajax-make-corrections/', 'data': { ...