TypeError: invalid ‘in’ operand obj

A weird JavaScript error that you may face when using Dojo Ajax for retrieving some JSON data from the server to render on the browser. This error happens because Dojo is unable to process the resulted JSON data which is the case when handleAs attribute is set to “text”.

In order to fix this error, set handleAs attribute to “json” instead of “text” as shown below in the example:

xhr.get({
	url: '/SomeServlet',
	handleAs: "json",
	timeout: 3000,
	load: function(data) { /* Success Handling */ },
	error: function(err) { /* Failure Handling */ }
});

This is my today’s two cent advice.

Iterate over a JSON object

One of the most useful advantages of the JSON format is that it is browser friendly. You donot need to write complicated code for navigating or iterating over a JSON structure. In this post, I will show you how to iterate over a JSON object.

Assume that you are having the following JSON object.

<script type="text/javascript">
var personStr = "{\"Name\":\"Hazem Saleh\",\"Occupation\":\"Software Engineer\",\"Nationality\":\"Egyptian\",\"Age\":\"102\"}";

var personObject = eval("(" + personStr + ")");
</script>

You may notice that I put the JavaScript String between parentheses. This is mandatory to avoid the json invalid label browser error.

if you want to simply iterate over the JSON object you should use the standard JavaScript for in loop as follows.

<script type="text/javascript">
for (var key in personObject) {
  if (personObject.hasOwnProperty(key)) {
    alert(key + " -> " + personObject[key]);
  }
}
</script>

I wish that this tip can be helpful to you.

window.open Invalid argument in IE

You may face the following error message in IE while working with the window.open JavaScript API:

Message: Invalid argument.
Line: 21
Char: 4
Code: 0
URI: ...

This error happens because IE does not allow spaces in the window name, for example the following code will cause the invalid argument error in IE:

window.open('test.htm','New Window','width=400,height=400');

To resolve this error, the solution is simple just remove the spaces from the window name and it will work fine:

window.open('test.htm','NewWindow','width=400,height=400');

Finally, the other interesting fact is that IE does not allow the window name to have dashes “-“, so you have to remove it from the window name to make the window.open API working fine in IE.