Ali Baig
Ali Baig

Reputation: 3867

Cross Domain Ajax (JSONP) Callback Issue

I have a code where i need to make cross domain requests to get the text/html as response. I've been using the JSONP method and was getting the results (json) before on some other program. When i run the program, console reports an error which is

 Uncaught SyntaxError: Unexpected token < 
 ?callback=jQuery17207555819984991103_1414157672145&_=1414157675836"

As you can see it has added an extra parameter value after the callback parameter which is causing an issue. When i see the response in Network tab, its pretty good and exactly what i wanted. I tested it on 4 cross domain links and that extra paramter is coming to all of them. Following is my code:

$.ajax({
                type: 'get',
                url: link,
                dataType: 'jsonp',
                success: function(dataWeGotViaJsonp){
                    alert(dataWeGotViaJsonp)
                    var len = dataWeGotViaJsonp.length;
                }
            });

The links I have passed to it:

 http://stackoverflow.com/questions/20944962/data-grid-view-update-edit-and-delete-in-vb-net-windows-form-that-using-multipl
 http://www.espncricinfo.com/pakistan-v-australia-2014/engine/match/727927.html
 http://pucit.edu.pk/

Response is good but due to that error, success callback isn't being called. Any solutions?

Upvotes: 0

Views: 280

Answers (1)

cshotton
cshotton

Reputation: 2830

"Uncaught SyntaxError: Unexpected token <" is an indication that the returned data is very likely HTML mark-up and not proper JSONP. In order to return HTML from a JSONP web service, you need something on the server that is wrapping the HTML in proper procedure call syntax. E.g.,

jQuery17207555819984991103_1414157672145 ("<div>... your HTML here ...</div>")

Since the HTML will likely have quote characters in it somewhere, you will need to escape, URL encode, UUEncode, or otherwise convert the HTML text to be an appropriate Javascript string, and then convert it back in the client.

As for the "_=1414157675836", this is being added to ensure the response is not cached. Unless your server's web service is rejecting the request because the "_" parameter is not recognized, this is a red herring. The problem is the bad JSONP syntax coming from the host.

Upvotes: 2

Related Questions