My javascript works in every browser but IE8 - javascript

By every browser, I mean Safari, Firefox, Chrome, and IE9.
Here is the error I'm getting in IE8's console:
'data.cities[...].country' is null or not an object
Line 374, which is below (var country = k.data.cities[i].country;):
downloadUrl(url, function(data) {
var k = eval("(" + data.responseText + ")");
var klength = k.data.cities.length;
var countries = [];
for(i=0; i < klength; i++) {
var country = k.data.cities[i].country;
countries.push(country);
}
countries = $.unique(countries);
var countryLength = countries.length;
for(i=0; i < countryLength; i++) {
$('.ribbon').append('' + countries[i] + '');
}
});
Why would IE8 be the only browser having a problem with this line? I know the data being fed is not null, as the same data is used to place objects on a map and they display just fine.

I suspect that the eval() function doesn't return what you expect.
You might want to try using JSON.parse instead.
You can find a parser there for browsers that don't have native support for JSON.

The problem is most probably that data.responseText might have a trailing comma somewhere.
[
"A", "B", "C",
]
This does not work for Internet Explorer and is also not valid JSON. All other browsers cope with the trailing comma.
Fix: Change your AJAX end point to omit all trailing commas.
Even better fix: Use JSON.parse which will bomb for non-valid JSON, so that all browser behave the same by failing.

Related

Can’t access unicode keys. Possibly, Javascript JSON parser bug?

I have a json string, that has Unicode key:
{"Текст":"Text"}
I can successfully JSON.parse it and then JSON.stringify – it will be the same.
I can’t access Текст key; it is undefined:
JSON.parse('{"Текст":"Text"}')["Текст"] // undefined
I can’t get keys by Object.keys(), it returns 0.
I tried to escape Unicode in string before parsing it, and even escape Unicode in brackets when trying to access a key, but it doesn’t help.
Page has
<meta charset="utf-8">
Json string is returned by php’s echo. Php code has at the beginning
header('Content-Type: text/html; charset=utf-8');
String by itself displays correctly.
Update
I changed content type to plain text to all script (can’t use pc and devtools, unfortunately), to see how the json string is echo. It is escaped:
...,"\u041d\u0430\u0447\u0430\u043b\u043e":"some value",...
Update 2
I changed escaped unicode to just unicode, but still facing the issues
Update 3
I think it is indeed a bug. As I wrote above, json object parsed from unicode string is absolutely valid. I can’t access it’s keys, but if I stringify it, it will return a valid string.
I thought: “what if to parse and then set key, that should be there?”. I did it – nothing is changed. And more – adding any key is not affecting a json object. When I stringify it, it returns an original string, without any changes.
Since native JSON stuff doesn’t work, I’ve made my own solution to set/get json keys:
function JSONget(j, k)
{
var i = j.search('"'+k+'"');
if(i == -1)
return j;
i+=k.length;
while(j[i] != ':' && i < j.length)
i++;
i++;
if(j[i]=='"')
i++;
var buffer = [];
for(var a=0; i < j.length; i++, a++)
{
if((j[i]=='"'&&j[i-1]!='\\')||(j[i]==','&&j[i+1]=='"'))
break;
buffer[a] = j[i];
}
return buffer.join('');
}
function JSONset(j, k, v)
{
var i = j.search('"'+k+'"');
if(i == -1)
return j;
i+=k.length;
while(j[i] != ':' && i < j.length)
i++;
i++;
if(j[i]=='"')
i++;
var buffer = [];
for(var a=0; i < j.length; i++, a++)
{
if((j[i]=='"'&&j[i-1]!='\\')||(j[i]==','&&j[i+1]=='"'))
break;
buffer[a] = j[i];
}
var t = j.split('"'+k+'"');
t[1] = t[1].replace(buffer.join(''), v);
return t[0]+('"'+k+'"')+t[1];
}
Use
JSONget('{"Текст":"Text"}', "Текст") // Text
JSONset('{"Текст":"Text"}', "Текст", "Latin vs Cyrillic") // "Текст":"Latin vs Cyrillic"

Code works in code tester but not in adressbar

If i input my code here:
http://writecodeonline.com/javascript/
It works as intended, but if i input it in my adressbar with "javascript:" infront the alert box just shows the original string.
What is going wrong?
var string = "Sunshine & Whiskey";
var stringFeedback;
var i = 0;
string = string.replace("&","%26");
do {
stringFeedback = string.search(/[ ]/);
string = string.replace(/[ ]/,"%20");
i += 1;
} while (i < 5);
alert(string);
Edit:
If i input in my Chromium console it works fine, but if i make a bookmark with the same code it doesn't.
Any suggestions on how to fix that?
Try initialising i before the loop:
var i = 0;
do {
stringFeedback = string.search(/[ ]/);
string = string.replace(/[ ]/,"%20");
i += 1;
} while (i < 5);
Whatever, I recommend you use your browser console to test these code snippets.
You can use
encodeURIComponent("Sunshine & Whiskey");
That returns
Sunshine%20%26%20Whiskey
without any loop, it's a native method of javascript that is supported by all Browser.
MDN documentation

How to test if array item's text contains a substring?

I've been doing research on testing if a value exists in an array, and keep getting matches for indexOf('textvalue').
But, my 'textvalue' will be a substring, and therefore won't pull a match. This is because I'm passing the field name to the method, and just need to delete the "Door: Front Left;" text by matching the array item on "Door". Does anyone know how I can accomplish this?
Here's the example code I'm working on:
(spnSelectedDisclosures will have a list of selected fields, and this is the code to remove the previous field selection from the text, which is semi-colon delimited.)
var currentText = $("#spnSelectedDisclosures").text();
var existingArr = currentText.split(";")
for (i=0;i < existingArr.length;i++) {
var indexItem = " " + existingArr[i].toString(); // why is this still an object, instead of a string? Adding a space to it was a desperate try to make indexItem a string variable.
if (indexItem.contains(substringText)) { // offending line, saying the object has no method 'contains'
alert("there's been a match at: " + i);
textToRemoveIndex = i;
break;
}
}
var textToRemove = existingArr[textToRemoveIndex];
var newText = currentText.replace(textToRemove,"");
$("#spnSelectedDisclosures").text(newText);
What's about this?
for (i=0;i < existingArr.length;i++) {
if (existingArr[i].indexOf(substringText) > -1) {
alert("there's been a match at: " + i);
textToRemoveIndex = i;
break;
}
}
String.contains() has very limited support:
Browser compatibility
Chrome Not supported
Firefox (Gecko) 19.0 (19)
Internet Explorer Not supported
Opera Not supported
Safari Not supported
You need to use a regular expression or indexOf.
if (indexItem.indexOf(substringText)!==-1) {

IE AJAX Responses Trim All Data After Null (0x00) Characters

In Internet Explorer (IE6, IE7, and IE8) null characters ("0x00") and any characters after are trimmed off of ajax responses (data).
I have a loop of AJAX requests like the following:
var pages = 10;
var nextnoteid = 0;
for (isub = 1; isub <= pages; isub++)
{
var c = "http://www.site.com/application.exe?id=" + nextnoteid;
$.ajax(
{
url: c,
cache: false,
async: false,
success: function(data)
{
var start = data.indexOf("NEXTNOTEID") + 10;
// save the id of the next note to retrieve
nextnoteid = data.substring(start, start + 16).trim();
data = data.substring(0, start - 10);
// append note to DOM
$("#printarea").append("<pre class='pxprintpage'>" + data + "</pre>");
}
});
}
The responses are returned in the following format (_ represents a 0x00 character):
Note Title
Note Author
... simple text note ...
__________NEXTNOTEID__________9827482998274829__________
How can I get this data after 0x00 in IE6, IE7, and IE8 without changing the respone?
I'm not sure if this will really help, but try setting the dataType field in the options passed to .ajax() to "text".
If that doesn't fix the issue, take a look at the dataFilter option passed to .ajax(). It allows you to specify a callback function to handle the raw response.
IE browsers like to terminate strings at NULL characters. The solution is to replace the null characters with spaces. Unfortunately, this appears to be the only solution, which does not exactly fit the question asked.

jquery conversion for this javascript

I have the following code:
for (i=1; i<=len; i++) {
var optcheck = col+'|'+document.getElementById('color').options[i].value;
text = document.getElementById('color').options[i].text.split(' - ');
}
This is part of the original code from javascript. I have successfully converted much of the other stuff into jquery but I can't seem to figure out how to convert this into jquery.
Please note that col is just value I am passing when calling the function which is usually "16"
Here is what I got so far:
for (i=1; i<=len; i++) {
var optcheck = col+'|'+$('#color').val(i);
text = $('#color').val(i).text.split(' - ');
}
Also, the original code works fine in Chrome, Firefox, Opera and Safari but in IE (all version from 6 to 9) I get an error saying 'options[...].value' is not null or not an object
Thanks for the help!
You're mis-calling val.
Change it to $('#color option').eq(i).text() and $('#color option').eq(i).val()
$('#color option').each(function() {
var a = col + '|' + this.value,
b = this.text.split(' - ');
// do stuff with a and b
});

Categories