I encountered some strange behaviour whilst testing out a web application I'd written in Internet Explorer 10. After some lengthy debugging, I discovered that, for whatever reason, IE10 doesn't like how I construct my JSON array. Couldn't find anything from trusty Google, all the related stuff was parsing AJAX results, or here on SO.
What I usually do
So I always constructed my JSON arrays just like this answer recommends:
item {};
item.propertyOne = prop1;
item.proprtyTwo = prop2;
...
In this particular case, I'm dynamically building up an array of objects based on some criteria. I have an array
which hold all of these objects, so I simply call push()
to add each object
into the array
:
var objects = [];
...
function addToArray(itemName, itemData){
item = {type: itemName, data: itemData};
objects.push(item);
}
I then pass this via AJAX to my PHP file, like so:
$.ajax({
type: 'POST',
url: 'https://someURL.com',
data:{data: JSON.stringify(objects)},
cache: false,
async: true,
timeout: 10000,
success: function (data) {
location.href='https://someotherURL.com';
},
error: function(XMLHttpRequest, textStatus, errorThrown){
console.log(textStatus + " : " +errorThrown );
}
});
And then I can do whatever I like with it in my PHP. This causes absolutely no issue in Chrome or Firefox.
The problem
So I realised today that I hadn't done any testing in IE since I implemented this functionality. I open up the webpage in IE and I get hit with the following console error:
error: internal server error
I've seen plenty of these before so I know the issue is originating from the AJAX error callback. After some debugging I narrow the issue down to the function above, in particularly this line:
item = {type: itemName, data: itemData};
In IE, this is evaluating to NULL
, so when it gets pushed into the array, the index is NULL
and the AJAX fails. Okay, at least I know where my issue is.
After some research, I cannot find anything which indicates why IE cannot parse this. It's perfectly valid syntax; it's working fine in two other browsers. I did, however, solve my problem by changing the syntactical structure to this:
var objects = [];
...
function addToArray(itemName, itemData){
objects.push( {type: itemName, data:itemData} );
}
So, my question is this - Why does this not work in IE10:
item = {type: itemName, data: itemData};
array.push(item);
But this does:
objects.push( {type: itemName, data:itemData} );
EDIT: After trying to reproduce the problem again upon correcting the solution, item
does not evaluate to NULL
, but rather:
item:
function item() {
[native code]
}
I think perhaps the NULL
may be originating from another source and the problem is in fact caused by the window.item
method in IE as mentioned by @Frederic