J0eBl4ck
J0eBl4ck

Reputation: 415

JSON issue with jQuery (JSONP)

I have a strange issue using jQuery and JSON, especially JSONP. My goal is to simply GET JSON data, but I always end up with the following error:

Uncaught SyntaxError: Unexpected token

Here is the code:

<script type="text/javascript">
     $(document).ready(function() {
      var myurl = "someurl";

     $.ajax({
            url: myurl,
            method: 'GET',
            contentType: 'application/javascript',
            dataType : 'jsonp',
            success: function(result){
                //Do something with JSON result
            }
    });
</script> 

And of course the JSON (raw format):

{"result":[{"targetView":"powerUsage","myData":{"someItems":["9","5","8"],"someItems2":[{"text":"protoText","currentRecord":"45.38","absolute":100}]}}]}

I tried the webservice with the Advanced Rest Client App in Google Chrome and it is working perfectly. I have no clue why this simple example gets this syntax error message.

Upvotes: 0

Views: 175

Answers (2)

Dhruv
Dhruv

Reputation: 173

You missed to put ready function close, that is }); at the last before script tag close:

<script type="text/javascript">
     $(document).ready(function()
     {
       var myurl = "someurl";

       $.ajax(
       {
         url: myurl,
         method: 'GET',
         contentType: 'application/javascript',
         dataType: 'jsonp',
         success: function(result)
         {
           //Do something with JSON result
         }
       });
     });
</script>

Upvotes: 0

Yogendra
Yogendra

Reputation: 2234

Your Ajax code looks like fine. I think you are trying to make a Cross domain call as JSONP is a hack for dealing cross domain ajax call. If you Server code if ready for dealing with JSONP request then you must have send a callback parameter like

?callback=my_callback_method

than you service will return result with a callback see below links for more details:

https://learn.jquery.com/ajax/working-with-jsonp/
http://stackoverflow.com/questions/11736431/make-cross-domain-ajax-jsonp-request-with-jquery

Upvotes: 1

Related Questions