IE8 is encountering a null JSON response from the HTTP handler, unlike IE10 and Chrome which are not experiencing this

Here is my JavaScript code snippet:

patients.prototype.GetPatient = function(patient_id,callback)
{
    var xmlhttp;
    var fullpath;

    try {

        if (window.XMLHttpRequest) {
            xmlhttp = new XMLHttpRequest();
        }
        else {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }

        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

                var pat = parseJson(xmlhttp.response);

                if (pat) {
                    callback(parseJson(xmlhttp.response));
                }
                else {
                    alert('Null object returned?');
                }
            }
            else if (xmlhttp.status == 404) {
                alert('Unable to find Retrieve Patient Service');
            }
        }

        xmlhttp.open("GET", "RetrievePatient.ashx?PatientId=" + patient_id, true);
        xmlhttp.send();

    }
    catch (e) {
        alert('Unable to retrieve requested patient details');
    }
}

function parseJson(jsonString) {
    var res;

    try {

        alert('Parsing JSON');

        res = JSON.parse(jsonString);

    }
    catch (e) {
        alert('Call to evaluate result failed with error ' + e.message + ' Evaluating Json ' + jsonString );
    };


    return res;
}

When executed in IE10 or Chrome, the patient details are returned successfully. However, when running on a page in IE8, the JSON data comes back as null causing the process to fail.

Does anyone have suggestions on how I can modify this code to work properly in IE8?

Answer №1

It's important to check for null and undefined before attempting to parse JSON data.

function parseJson(jsonString) {
   var result;

   if (jsonString == undefined || jsonString == null) {
       return jsonString;
   }

   if (window.JSON && window.JSON.parse ) {
       result = JSON.parse(jsonString);
       return result;
   }

}

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

How can I properly redirect an HTTP request to HTTPS on my Express server?

Currently, I am working on my API and have configured it to work with the HTTPS protocol using SSL. Here is the code snippet: https.createServer({ key: fs.readFileSync(certKeySSLPath), cert: fs.readFileSync(certSSLPath) }, app).listen(serverPORTHTT ...

Utilizing API pointers in JSON PHP programming

Currently, I am diving into the world of JSON and PHP through APIs. The issue I am facing involves extracting data from Array 0. The output can be viewed at the bottom by following the link. I have searched extensively for solutions online, but I am still ...

"Extending Material-UI: Utilizing Multiple Snackbar Components

I've been struggling to display multiple warnings using Snackbar from the Material UI library in my React project. I haven't found any examples with React, only Vue. Can anyone help me with this? Here is the code that I have tried so far: https: ...

Turn off Chrome Autofill feature when placeholders are being used in forms

I am encountering difficulties with Google autofill for fields that have placeholders. Despite attempting various solutions provided at: Disabling Chrome Autofill, none of them seem to work as needed. The challenge is to create a form with different field ...

I am looking to implement a required alert for a radio button that mimics HTML5. How can

When using the input type text, adding the required attribute prevents the form from submitting and prompts the browser to focus on the required field with an alert instructing to fill it out. On the other hand, when applying the required attribute to t ...

Exploring nested dictionaries in Swift: accessing a dictionary inside an object contained within another

Utilizing the Yellow Pages API, I am able to access business listings based on the phone's location. The results are returned in JSON format and I have successfully parsed it: do { let searchResultsData = try NSJSONSerialization.JSONObjectWithDa ...

Utilizing the click event with a Bootstrap modal: A guide

I have a PHP script that generates multiple Bootstrap modals, and I want to be able to modify some input fields when the "save changes" button is clicked. The ModalIDs generated are in the format "ModalID0000". However, nothing happens when I click on the ...

Blank area located at the bottom of the document

I'm having trouble designing a webpage without a scroll bar because there isn't much content to display on the page. I've tried searching for solutions and following steps to fix the issue, but I haven't had any success. If anyone can a ...

When the value is removed, it does not revert back to the initial filtered choices

After clearing the input, I want to display all the original li's again. The issue is that even though .value = '' clears the input, the filter remains active. I could really use some help with this as it's starting to get on my nerves ...

In this JavaScript tool for counting characters, every carriage return is counted as two characters

Hello there! I have created a character counter in JavaScript that looks like this: <textarea class="SmsText" id="txttemplate" maxlength="160" /> <span id="charsCount">160</span></strong><span>character(s) left</span> ...

Javascript/jquery functions perfectly in all browsers except Firefox

This particular piece of code seems to be functioning properly in Internet Explorer 8, Chrome, and Safari, however, it is not working as expected in Firefox: <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></scr ...

HTML image identifier and canvas elements

Greetings! I have a question that I've been struggling to find an answer for on Google. I'm attempting to draw an image on a canvas and initially used the "new" constructor ( ballPic = new Image(); ballPic.src = "ball.png" ) which worked fine. Ho ...

Text field auto-saving within an iFrame using localStorage is not functioning as expected

My goal is to create a rich text editor with an autosave feature using an iframe. Although each code part works individually, I am struggling to combine them effectively. View LIVEDEMO This graphic illustrates what I aim to accomplish: The editable iFram ...

Vue is alerting me that I cannot assign a reactive property to an undefined, null, or primitive value, specifically null

When retrieving data from Firebase, I am attempting to update the properties of the object being displayed on the UI. However, whenever I try to make any changes to the data, an error is thrown. Error in v-on handler: "TypeError: Cannot use 'in&apos ...

Parsing XML using Java's E Mapper library and converting it to JSON with Objectmapper

I have a question for you. I am trying to convert a simple XML file to a JSON file. The conversion is successful, but the output I receive is not properly formatted. Here are the files: modalities.xml <cons> <modalities type="mod"> ...

Updating a particular value within a JSON file

I'm searching for a method to locate a specific json value by its name and set it to null. The json file's structure can vary, it is not always consistent. Let's assume the json appears like this: [ { "id": "1111", ...

The HttpParams are reluctant to be established

Working with Angular 8, I am attempting to assign an HttpParam using the provided code snippet and observing the outcome on the final line. let newParams = new HttpParams(); newParams.set('ordering', 'name'); console.log('getting: ...

Converting JSON data into a Dictionary format

I am trying to deserialize a Json object into the Config class shown below: public class Config { public String Name { get; set; } public SSOType Type { get; set; } public Dictionary<String, String> Configuration { get; set; } } The goa ...

JavaScript timing the completion of AJAX requests

I'm working on a basic ajax request using js and php to fetch data from mysql. Check out the code snippet below: function ajax_function(a,b) { $.ajax({ type : 'POST', url : mine.ajax_url, dataType : 'json&ap ...

AngularJS does not update values properly if there is a style applied to the parent container

I'm struggling to find the best approach to handle this situation. This is how my AngularJS code looks: <span class="something" ng-hide="onsomecondition"> {{value}} </span> .something{ text-align:left; padding:10px;} Issue: The value ...