3

I have following code

<html>
<head>
    <script src="jquery-2.1.4.js."></script>
    <script>
        $(document).ready(function(){
            $.ajax({
                url: 'https://www.google.co.in/?gfe_rd=cr&ei=mezSVeG9Cqat8wf92o2oDg',
                dataType: 'jsonp',
                success: function(dataWeGotViaJsonp){
                console.log(dataWeGotViaJsonp);
                }
            });
        })
    </script>
</head>

I am getting output on console as

Uncaught SyntaxError: Unexpected token < ?gfe_rd=cr&ei=mezSVeG9Cqat8wf92o2oDg&callback=jQuery21407372110611759126_1439888764171&_=1439888764…:1 

What can be the issue?

newhorizens
  • 107
  • 1
  • 9

1 Answers1

1

You make an AJAX request and the answer is supposed to be a JSON object. Or a JavaScript function call if you use JSONP.
However, the response is the following HTML:

<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="ru"><head><meta content="/images/google_favicon_128.png" itemprop="image"><meta content="origin" id="mref" name="referrer"><title>Google</title>  

As the first character in a response string is a tag opening, it cannot parse < and returns an error.

Are you making a request to the wrong URL?

Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
  • Ok I am just learning jQuery & AJAX, I am not getting answer as JASON object & it's HTML that is right. So I get error.What are success and error conditions for AJAX requests? – newhorizens Aug 18 '15 at 09:24
  • You don't need to use AJAX for requesting HTML pages. AJAX request is usually used to get data without reloading of page and dynamically update a page. It can return plain text, XML, JSON. Please, read this article: http://stackoverflow.com/questions/6009206/what-is-ajax-and-how-does-it-work – Yeldar Kurmangaliyev Aug 18 '15 at 09:26
  • I have xml file on server which is in another domain from my application domain.How should I fetch it? I tried JSONP for that purpose only i.e. CORS limitation. – newhorizens Aug 18 '15 at 11:02
  • You cannot fetch XML file with JSONP. JSONP assumes JavaScript code. So, if you want to avoid CORS limitations and make a JSONP request, your server should return a JavaScript call with response object. Something like `callback({"data": "someData", "id": 1});`. Unfortunatelly, you can do nothing with XML file in another domain if it's `Accept-Control-Allow-Origin` is not allowing your host. – Yeldar Kurmangaliyev Aug 18 '15 at 11:08