What is causing this JSON to malfunction in Internet Explorer?

Everything is functioning well on Chrome and other browsers except for IE. Below is an example to illustrate:

(specifically referring to IE 8, unsure about compatibility with IE 9)

Upon running the JSON request, I encountered an error stating "Object expected" on line 29.

<!DOCTYPE html> 
<html> 
  <head> 
  <title>Sandbox</title> 
    <script src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
</head> 
<script>

function search()
{
    $.ajax({ 
        url: 'http://davzy.com/cache/api/rarevalues.php?callback=?&search=' + $('input').val(),
        cache: false,
        dataType: 'json',
        success: function(data, status, xhr) {
            $('body').append('<br>' + data[0].name);
            $('input').focus().val('');
        }
    });
}

</script>
<body> 
    <div>type test or rare or chair</div>
    <input onkeydown='if(event.keyCode == 13) search();'>
    <button onclick='search()'>Go</button>
</body>
</html>

Below is a snippet of the JSON response (the callback functions as expected, ignore the "?", source: )

    ?([{"0":"18","id":"18","1":"Petal Patch","name":"Petal Patch","2":"75","parent":"75","3":"cache\/rare_values\/images\/petal_patch.gif","small_image":"cache\/rare_values\/images\/petal_patch.gif","4":"cache\/rare_values\/images\/large\/petal_patch.gif","big_image":"cache\/rare_values\/images\/large\/petal_patch.gif","5":"A little bit of outdoors indoors..","motto":"A little bit of outdoors indoors..","6":"0","displayorder":"0","7":"1_center cache\/rare_values\/images\/petal_patch_1.png\n1_left cache\/rare_values\/images\/petal_patch_2.png","interactiveimages":"1_center cache\/rare_values\/images\/petal_patch_1.png\n1_left cache\/rare_values\/images\/petal_patch_2.png","hcs":12.5,"throne":0.06,"credits":"25"},{"0":"685","id":"685","1":"Petals","name":"Petals","2":"28","parent":"28","3":"cache\/rare_values\/images\/petal_flurry.gif","small_image":"cache\/rare_values\/images\/petal_flurry.gif","4":"cache\/rare_values\/images\/large\/petal_flurry.gif","big_image":"cache\/rare_values\/images\/large\/petal_flurry.gif","5":"Romance is in the air. And so are rose petals apparently.","motto":"Romance is in the air. And so are rose petals apparently.","6":"0","displayorder":"0","7":"","interactiveimages":"","hcs":1.5,"throne":0.01,"credits":"3"}])

Following Strimp099's advice, including header('content-type: application/json; charset=utf-8'); resolved the issue with IE. Appreciate the help!

Answer №1

After some trial and error, I realized that adding header('content-type: application/json; charset=utf-8'); was the missing piece to make my code work properly in IE as JSON. Lesson learned! Big thanks to Strimp099 for pointing me in the right direction.

Answer №2

For a comprehensive explanation, you can visit this link: JavaScript KeyCode Values are "undefined" in Internet Explorer 8

Consider using the following approach instead:

var keyCode = (window.Event) ? e.which : e.keyCode;
if (keyCode == 13) {
    search();
}

You may also want to check if your button is triggering the search function twice when hitting enter on the input field. To resolve this issue, try changing:

<button onclick='search()'>Go</button>

to:

<input type="text" onclick='search()' value="Go" />
?

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

Can a simultaneous read/write conflict occur in JavaScript while browsing?

A situation has arisen where I am executing multiple (let's say four) AJAX calls using AngularJS http get, and I desire each call to invoke a callback function that increments a counter. This way, I can track when all four threads have finished. I am ...

What could be the reason why the angular time picker is not showing any

After using a time picker for booking and storing it in the database, I encountered an error while trying to pass the time to the input field during editing. Error: [ngModel:datefmt] Expected `01:00:00 pm` to be a date http://errors.angularjs.org/1.3.13/n ...

Using JS regular expressions to only select anchor (a) tags with specific attributes

When trying to select a link tag (a) with a specific data-attr, I encountered an issue. I currently use the following regex pattern: /<a.*?data-extra-url=".*?<\/a>/g. However, I noticed that this selection goes wrong when there are no line br ...

Determine whether either of these elements has the mouse hovering over it using jQuery

In my DOM, I have two separate elements that need to change when either one is hovered over. If the link is hovered over, not only does the image src need to change (which is easy), but also the link color needs to change. Similarly, if the image is hovere ...

When attempting to use a value outside of its block, the function may return a

My current task involves querying one collection to retrieve IDs, then using those IDs to query another collection and send back the response. The process runs smoothly until I encounter an issue with retrieving values outside of a block when using forEach ...

What is the best way to prevent event propagation while still allowing a modal to function correctly?

I have a scenario where I want to prevent a table row (<tr>) from receiving a click event when one of two buttons inside it is clicked. To achieve this, I've added an event handler that stops the propagation of the click event. $(".btn").on(&ap ...

Is it feasible to send a JavaScript prompt response to my SQL database, or is there a more effective method to achieve this task?

I currently have the following code triggered by an HTML button: function popup() { var group = prompt("Please enter group name"); if (group != null || group != "") { window.location.href = "template.php?groupid=&qu ...

Tips for setting up the image as the header background in HTML5 and CSS3

I am currently designing a website. I'm wondering if there is a way to create a div with a curved bottom using HTML5, CSS3 and JavaScript. It should resemble the design of the curved header bottom ...

There seems to be an issue with node.js - headers cannot be set after they have already been sent to

As I work on developing my blog, I've encountered an issue with rendering different paths using the router parameter. Each time I attempt to display another route, an error surfaces. Unfortunately, I'm unable to provide more details at this momen ...

Using jQuery to add a checkbox to a list that is not ordered

My HTML structure includes an unordered list with nested lists. Here is a snippet of the code: <div id="checklist"> <ul> <li>On Page SEO <ul> <li>My work <i>And note.</i>< ...

The pdf generation feature of pdf-creator-node in Linux seems to be malfunctioning

An error occurred with code EPIPE at afterWriteDispatched (internal/stream_base_commons.js:154:25) at writeGeneric (internal/stream_base_commons.js:145:3) at Socket._writeGeneric (net.js:784:11) at Socket._write (net.js:796:8) ...

Learn how to showcase video information in a vue.js template

I am having difficulty displaying a saved media (video) file on another page after collecting it using the ckeditor5 media option. The data is stored along with HTML tags generated by ckeditor, so I'm using v-html to display other content like <p&g ...

Obtaining Data from Fetch Response Instance

Currently, I am utilizing the fetch method to execute API requests. While everything is functioning as expected, I have encountered a challenge with one specific API call due to the fact that it returns a string instead of an object. Normally, the API pro ...

Styles not applied to React.js components when page is refreshed

I'm encountering an issue while using React in combination with react-router and material ui. Upon the initial page load, everything appears as expected. However, if I refresh the page, all styles seem to disappear. If I make changes to the code and ...

Skipping a JSON field in HTML/JavaScript when it is blank: A guide for developers

To develop an interactive program based on JSON input, I aim to display headers, subheaders, and choices derived from the JSON data. Some input fields may remain unfilled. For instance: Header Subheader Choice 1 Choice 2 Subheader2 Choice ...

Preventing JSON serialization of return values in ASP.NET WebMethod

Utilizing JQuery and a WebMethod, I am sending and storing the string representation of a JSON object in my database. Similarly, there is another WebMethod designed to retrieve user settings from the database and send them back to the requesting client: ...

What is the best way to iterate through multiple arrays using a single for loop

I have various hidden popups that are triggered to show on click using some JavaScript magic. As a beginner in JavaScript, I find myself writing multiple lines of code that look very similar. Currently, my code for handling these popup boxes looks like th ...

Custom geometry in Three.js raycaster detects incorrect object

I am facing a challenge with the default cube's appearance in wireframe mode, as it is made up of triangles instead of squares. To combat this, I created my own geometry which looks satisfactory. However, I have noticed that the raycaster does not fu ...

Tips for utilizing the value of object1.property as a property for object2

Within the template of my angular component, I am attempting to accomplish the following: <div> {{object1.some_property.(get value from object2.property and use it here, as it is a property of object1)}} </div> Is there a way to achieve this ...

"Enhance your Vue components with a directive to customize or adjust element attributes

I have a variety of elements structured like this: <some-custom-component :errors="formErrors.has(getErrorKey('town'))" :error-messages="formErrors.getAll(getErrorKey('town'))" ></some-custom-component> The formErrors ...