When using phonegap with iOS, HTTP requests consistently return a status of 0 when accessing local files

I've encountered an issue while using Phonegap 3.3.0 on iOS. The HTTP request I'm making always returns 0, regardless of whether the file exists or not!

var url = './images/pros/imagefile.png'; 
var http = new XMLHttpRequest(); 
http.open('HEAD', url, false); 
http.send(); 
http.status 

Even when trying a fake wrong URL:

var url = 'httpbabla/images/pros/imagefile.pngfkjdqmkfjdmqsl'; 

or

var url = 'www/images/pros/imagefidddddddle.pngooijijijiojs'; 

The result remains 0.

Could this be a bug in Phonegap? If not, what is the best way to differentiate between existing local files and nonexistent files using Phonegap on iOS?

Thank you

Answer №1

To increase your chances of success, consider using an asynchronous request with the onload and onerror handlers. Make sure to include a true parameter as the last argument in the http.open method:

var url = 'file:///does/not/exist.jpg'; 
var http = new XMLHttpRequest(); 
http.open('HEAD', url, true); 
http.onload = function(e){/* Success! File exists; process the response... */};
http.onerror = function(e){/* Failed - file does not exist - handle accordingly... */};
http.send(); 

After calling http.send, your function will be completed and control will go back to the caller. Any further processing for success or failure should be handled within the onload and onerror callbacks. If you are not familiar with them, take the time to understand Javascript callbacks (and closures) as they are powerful features in the language.

Answer №2

This is the solution that worked for me:


function CheckUrlValidity(url) {
    if (isPhoneGap && isIOS()) {
        if (url.fileExists()) { //refer to function below
            return true;
        } else {
            return false;
        }
    } else {
        try {
            http = new XMLHttpRequest();
            http.open("HEAD", url, false);
            http.send();
        } catch (err) {
            //alert("An error:" + err.name + "---" + err.message);
        }

        if (http.readyState == 4) {
            console.log("http.status=" + http.status);
            return http.status == 200 || http.status == 0;
        }
    }
}

// check if local file exists for iOS
String.prototype.fileExists = function() {
    filename = this.trim();
    var response = jQuery.ajax({
        url: filename,
        type: 'HEAD',
        async: false
    }).status;
    return (response != "200") ? false : true;
}

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

Tips on how to properly format a DateTime String

I need help with formatting a DateTime string retrieved from an API where it is in the format of YYYY-MM-DDTHH:MM:SS +08:00 and I want to change it to DD-MM-YY HH:MM getDataFromApi(res) { this.timestamp = this.timestamp.items[0].timestamp; console ...

Using Strapi to showcase images in a React frontend

I am currently in the process of developing a website utilizing Strapi as a Content Management System (CMS) and Next.js with React for the Frontend. The website features an image slider that includes an image, a headline, and a description. While I have su ...

JavaScript and CSOM updates cause SharePoint list item properties to disappear

Within my SharePoint environment, there exists a website where users can load a single list item based on their selection using JavaScript and CSOM. This particular list item contains approximately 60 properties defined in its list definition. Users have ...

Combining null and decimal validation into a single function in Asp .Net - JavaScript

How can I ensure that my Textbox is validated using Javascript? Specifically, I want to make sure that the TextBox is not empty and that only two digits are allowed after the decimal point. Additionally, I would like to restrict any other characters exce ...

I am dynamically generating table rows and populating them with data. However, I encountered an issue with retrieving the data by their respective IDs

Creating a table row dynamically by populating it with data. However, encountering an issue with retrieving the data by their respective id. if(xmlhttp.status == 200) { var adminList = xmlhttp.responseJ ...

"Using Jest to specifically test the functionality of returning strings within an object

Attempting to run a jest test, it seemed like the issue was with the expect, toBe section as I believed that the two objects being compared (data, geonames) were exactly the same. However, upon closer inspection, they turned out to be different. The struct ...

Loop through an array of objects, then store each one in MongoDB

If I receive an Array of Objects from a Facebook endpoint, how can I save each Object into my MongoDB? What is the best way to iterate over the returned Array and then store it in my mongoDB? :) The code snippet below shows how I fetch data from the Face ...

Sending multiple unique forms with the same structure using JavaScript and Ajax on a single PHP page

In my PHP page, there are 12 individual forms with unique form IDs, checkboxes, and dropdowns. Take a look at this image: https://i.stack.imgur.com/pODzk.png Each form has an Update Zone that fetches Name, Enable status, Time, Dim information, and sends ...

Building a local database using the MVC framework concept

Can a locally stored database be developed using MVC framework principles in javascript and html5? Thank you Ravindran ...

Instructions for generating multiple components in React when an array is not at your disposal

In the process of developing a Tic-Tac-Toe game, I am in need of creating 9 empty squares. Currently, I have a ul element and 9 li elements representing each square in the game. The issue is that there is no array available for looping through and generati ...

Achieve the appearance of table-like alignment without the need for traditional tables

Any ideas on how to achieve the following layout: <table border="0"> <tbody> <tr> <td style="margin-right:5px;"> <h2 id="optiona" class="option optiona optiona2">a. aa </h2> </td> ...

Styling the active selection in nav class with bold attribute in Bootstrap/AngularJs

How can I apply the bold attribute to the currently selected nav bar item? <ul class="nav"> <li role="presentation" ng-repeate="item in items" ng-class="{'active':navLink == item.header}"> </li> &l ...

What is the best way to access the current value and name of a textbox in real-time using

How can I retrieve the value of a textbox in JavaScript using onblur and on keyup events, while also performing real-time checking for each individual textbox using "this keyword"? Here is my JSFiddle link. Can you assist me in modifying it? ...

The compatibility between Laravel's @vite('resources/js/app.js') and the froala editor plugin seems to be causing issues

I have incorporated a Vue.js based commenting system and inbox messages system in my Laravel website. Additionally, I am utilizing a wysiwyg editor (Froala Editor) in my forms for uploading projects. The issue I am facing is that the Froala Editor does no ...

Tips for sending query string parameters to an AJAX request using data

Currently, I am making an ajax call to hit the API and I need to include a query parameter. How can I accomplish this with my ajax call? Below is the code snippet that I am using. Any assistance on this matter would be greatly appreciated. Thank you. ...

ng-admin fails to identify custom field view

I've been exploring ng-admin. After referring to the documentation, I decided to create a custom field. However, even though ng-admin recognizes the FooFieldType, it is not rendering the FoofieldView and instead using the original FieldView! Conf ...

Guide to enclosing selected text within a span tag and positioning a div in relation to it using JavaScript

My main objective is to enable the user to: highlight text within a paragraph enclose the highlighted text in a span element add an action button or div at the end of the selected text for further interaction Here's the code I've worked on so ...

Encountering issues while running the npm build command due to exporting async functions in React

In my React project, I am utilizing async functions and have created a file named apiRequest.js structured like this: const axios = require('axios'); const serverURL = "http://localhost:8080" getInfo = async function ({email}) { try { r ...

I am encountering a situation in which the controller file is returning empty data when logging the contents of req

User Model const mongoose = require("mongoose"); const userSchema = mongoose.Schema( { name: { type: String, required: true }, email: { type: String, unique: true, required: true }, password: { type: String, required: true }, pic: { ...

Only certain fields are returned by JQuery's form serialize() method

Encountering an issue with the serialize() function in jQuery when attempting to submit a serialized form via AJAX. Some of the field values are not being retained. Suspecting a problem with either my HTML structure or jQuery code: <div id="register" ...