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

toggle the outer div along with its corresponding inner div simultaneously

On one of my pages (let's call it "page1"), I have multiple divs, some nested within others. These divs are initially hidden and toggle on when a specific link is clicked (and off when clicked again). To view a nested div, the outer div must be opened ...

Detach an item from its parent once it has been added to an array

Currently, I am facing an issue with a form on my blog. The blog is represented as an object that contains multiple content objects within it. I seem to be experiencing some confusion because the reactivity of the content I add to the Array persists with t ...

REGEX: All characters that appear between two specified words

Is it possible to use Regex to select all characters within the designated words "Word1 :" and "Word2 :"? I am looking to extract any character located between these two specific phrases. Word1 : Lorem ipsum dolor sit amet consectetur adipiscing elit ...

Combining the keys of two objects in JSON

console.log(a) ; // output in console window= 1 console.log(b);// output in console window= 2 var c = {a : b};// Is there a better way to do this? var d = JSON.stringify(c); d = encodeURIComponent(d); I want the final value of d to be {1:2}. ...

Paste the current webpage's URL into a fresh alert popup using javascript"

I found myself spending hours trying to figure out the best way to create a JavaScript function that would copy the current URL and display it in a new alert window. Imagine a scenario where a user clicks on "Share this page" and a new alert window pops u ...

Sequelize cannot locate the specified column in the database

click here for image description I encountered an issue where a column was not recognized after migrating with sequelize-cli. Even though all the columns are defined in the migration file, this error keeps appearing. Additionally, when trying to create a ...

Regular expressions: understanding greedy versus lazy quantifiers

Imagine this situation: a = 'one\\two\\three.txt'; The desired output is "three.txt". However, the attempted solution of: a.match(/\\(.+?)$/) is unsuccessful. What could be causing this issue? How can we successf ...

Convert this text into HTML code: "Textarea to

I have a basic <textarea> element that I want to transform links (www.google.com, msn.com, etc) and line breaks (\r\n) into HTML code. I found one library for converting links into <a hrefs>. Another library can convert line breaks i ...

Passing a variable from index.html to a script in Angular

I am attempting to pass the array variable 'series' to the script in HTML. Is there a way to do this? app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app ...

Issue: Module 'xml2json' not found

Encountered an error while running my project package. When I tried to install the necessary packages using npm install xml2json I still encountered another error below. Can anyone provide suggestions or ideas on how to resolve this issue? D:\xa ...

What could be causing the error message "Error: Error serializing ___ returned from getStaticProps" to appear?

When I make a call inside getStaticProps, I keep encountering the error below and I'm struggling to understand why: Error: Error serializing `.lingo` returned from `getStaticProps` in "/". Reason: `undefined` cannot be serialized as JSON. T ...

Convert the value to JSON format by utilizing the PHP GET method

After retrieving a value using the GET method in my PHP file, I am attempting to access it. Below is how my PHP file appears: <?php include 'Con.php'; header('content-Type: application/json'); $catid = $_GET["CatId"]; //array ...

Tips for integrating Apache Solr with Cassandra without using DataStax Enterprise (DSE)

Embarking on a new project, I find myself utilizing Cassandra as the chosen DBMS, with Apache Solr serving as the search engine and Node.js powering the server scripting language. While I am well-versed in Node.js, Cassandra and Solr are unfamiliar territ ...

Using JavaScript and node.js, make sure to wait for the response from socket.on before proceeding

My task involves retrieving information from the server on the client side. When a client first connects to the server, this is what happens: socket.on('adduser', function(username){ // miscellaneous code to set num_player and other variabl ...

Where can I find the complete specification for the Calendarific JSON format?

I am interested in utilizing the Calendarific API for calculating working days in different regions. While the JSON response is informative, I am unable to locate a comprehensive definition of the fields within the API. In particular, I am seeking detail ...

Proper syntax for SVG props in JSX

I have developed a small React component that primarily consists of an SVG being returned. My goal is to pass a fill color to the React component and have the SVG use this color. When calling the SVG component, I do so like this: <Icon fillColour="#f ...

Overlapping problem with setInterval

I am currently working on a project that requires the use of both setInterval and setTimeout. I am using setTimeout with dynamic delays passed to it. While elements are not timed out, I have implemented setInterval to print out numbers. Here is the code ...

Can a single shield protect every part of an Angular application?

I have configured my application in a way where most components are protected, but the main page "/" is still accessible to users. I am looking for a solution that would automatically redirect unauthenticated users to "/login" without having to make every ...

Is there a way to eliminate the line that appears during TypeScript compilation of a RequireJS module which reads: Object.defineProperty(exports, "__esModule", { value: true });?

Here is the structure of my tsconfig.json file: { "compileOnSave": true, "compilerOptions": { "module": "amd", "noImplicitAny": false, "removeComments": false, "preserveConstEnums": true, "strictNullChecks": ...

Phonegap's JavaScript canvas feature is experiencing issues

Recently, I came across a JavaScript bouncing ball animation that works perfectly on the Chrome browser when used on a PC. However, when I tried running it using Phonegap Eclipse Android emulator, I encountered an issue where the canvas appeared blank and ...