MatthewSot
MatthewSot

Reputation: 3594

jQuery $.Get not working correctly

I'm having a problem with $.get that I've never had before, and can't seem to be able to fix it. When calling the following function:

function getDefinition (word) {
var toget = "http://www.stands4.com/services/v1/defs.aspx?tokenid=TOKEN&word=" + word;
jQuery.support.cors = true;
$.get(toget, function (data) {
    if(data.indexOf("<definition>") !== -1)
    {
        var definition = data.split("<definition>")[1].split("</definition>")[0];
        return definition;
    }
    else
    {
        return false;
    }
});

}

Internet Explorer (I've not tested it on other browsers) throws

"SCRIPT438: Object doesn't support property or method 'indexOf' randomfunctions.js, line 5 character 3" (line 5 character 3 would be the "i" in "if")

Earlier I was getting a CORS error, so I added the

jQuery.support.cors = true; 

line. I've attempted to alert(data), but the same thing happens. I'm using jQuery 1.6.1.

any help would be greatly appreciated, Matthew

Upvotes: 0

Views: 196

Answers (2)

jfriend00
jfriend00

Reputation: 707178

The first thing to do is to set a breakpoint in the debugger right before the .indexOf() call and examine the data variable to see if it's what you're expecting and if it has that method or not. Since we don't know what that data is, that's hard for us to say, but obviously IE is having difficulty with that.

.indexOf() can be a method on a string or an array. The array version is relatively new and some older browsers (or behind the times browsers) don't yet have support for it. If data was an array, that could be the issue. If that was the case, then you can either replace .indexOf() with a manual search through the array or add an ES5 shim for .indexOf(). There's a shim implementation of Array.indexOf() here on mdn.

It also looks like you're trying to return your data from the success handler of the $.get() call. That doesn't work. The success function is called by the internals of the ajax engine. Returning data to it does nothing - the data will just be dropped.

From an asynchronous ajax call (which$.get() is by default), you can't return your data from that suucess handler or from the .get() call. The data is only available in the success handler which happens sometime later. Instead, you must put any code that uses that data in the success handler or in a function call that gets called from the success handler. That's how asynch ajax calls must work. You can do traditional sequential programming with them.

Upvotes: 2

kinakuta
kinakuta

Reputation: 9037

If you're using an older version of IE, then indexOf may not be supported:

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf

Upvotes: 1

Related Questions