-1

I have a GET API that gives me the following result:

enter image description here

The following code, tries to get this JSON information:

<script>
   jQuery(document).ready(function ($)
   {       
      $.ajax({
         url: 'http://localhost:15840' + '/totem/GetRestaurants',
         type: "GET",
         dataType: "jsonp",
         crossDomain: true,
         complete: function (data)
         { 
            alert (data)
            for (var restaurant in data)
            {
               document.getElementById('restaurants').innerHTML = '<li class="gallery-image" > <a href="3.html" class="thumb"><img src="img/restaurante-02.jpg" alt="" /><div class="gallery-text"><span>FOOD RESTAURANT</span></div></a></li >'
             }   
          },
          error: function () {
             alert("error");
          }
       });
    });
</script>

The error method always get executed, and the complete alert just shows the following information:

enter image description here

But If I go to chrome inspector, the responce looks good:

enter image description here

enter image description here

Why is this happening?

EDIT:

With the following code, nothing happens:

<script>
    jQuery(document).ready(function ($)
    {       
        $.ajax({
            url: 'http://localhost:15840' + '/totem/GetRestaurants',
            type: "GET",
            dataType: "jsonp",
            crossDomain: true,
            success: function (data)
            {
                alert ("hello success")
            }
        });
    });
</script>
Lechucico
  • 1,914
  • 7
  • 27
  • 60
  • 2
    The error callback will tell you the problem. `error: function(err){ console.log(err); }` – Jamiec Mar 19 '19 at 11:37
  • 7
    Try using `success` instead of `complete` in your object passed to request. – Harish Kommuri Mar 19 '19 at 11:37
  • @Harish if I set success it never reaches. – Lechucico Mar 19 '19 at 11:41
  • Possible duplicate of [How to get the jQuery $.ajax error response text?](https://stackoverflow.com/questions/1637019/how-to-get-the-jquery-ajax-error-response-text) – Liam Mar 19 '19 at 11:41
  • @Lechucico as Harish said, try using success – Mrunmay Deswandikar Mar 19 '19 at 11:43
  • 3
    Your `data` is, presumably, an object (after the JSON is parsed). `alert` expects a string, and when it is passed an object, it stringifies it - which by default produces the rather unhelpful `[object Object]` you see. Everything else you do with the data should work fine, but `alert` will do this. The console allows you to see what's in the object, but `alert` (and other things which simply coerce the data to a string) do not. – Robin Zigmond Mar 19 '19 at 11:44
  • Try console.log instead of alert inside complete to see if it gets rid of the error callback. – user2648008 Mar 19 '19 at 11:46
  • If I just use success, nothing happens. See EDIT. – Lechucico Mar 19 '19 at 11:49

2 Answers2

1

You said:

dataType: "jsonp",

… but the screenshot of the response shows that is JSON not JSONP.

You need to either:

  1. Set the dataType to "json"
  2. Change the server to respond with JSONP (see What is JSONP, and why was it created? for more information on that).

Note that JSONP is a dirty and dangerous hack to work around the Same Origin Policy and that we now have CORS (which is a well-standardised and flexible means to selectively disable the Same Origin Policy that doesn't have JSONPs drawbacks). So don't go with option 2.


You might have tried using dataType: "jsonp" because you got an error like:

XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header

This error occurs because you are violating the Same Origin Policy. JSONP is one way to work around it, CORS is a better way. Both of those ways require the server to be changed to allow them to work.

See this question for more information.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • What I have to change on my .NET ASP c# backend to achieve this? – Lechucico Mar 19 '19 at 11:55
  • @Lechucico — [This question](https://stackoverflow.com/questions/35553500/xmlhttprequest-cannot-load-xxx-no-access-control-allow-origin-header/35553666#35553666) (which I referenced in this answer) says *The specifics of how you set that response header depend on Bob's HTTP server and/or server-side programming language. There is a [collection of guides for various common configurations](https://enable-cors.org/server.html) that might help.* which has [this section about ASP.NET](https://enable-cors.org/server_aspnet.html). – Quentin Mar 19 '19 at 11:57
0

As you are sending the jsonp request, you need to change how you are returning data. you need to wrap your JSON object in $_GET['callback']. if your backend was in php you can try the following code

 $response['data'] = array('sdu');
 $response = json_encode($response);
 echo htmlspecialchars($_GET['callback']) . '(' . $response . ')';
 exit;
Sumit Parkash
  • 196
  • 2
  • 7
  • `header("access-control-allow-origin: *");` is pointless if you use JSONP – Quentin Mar 19 '19 at 11:49
  • `text/javascript` is obsolete. The correct MIME type for JavaScript is `application/javascript`. – Quentin Mar 19 '19 at 11:49
  • @Quentin you are right, we can ignore the header part. I have edited my answer. – Sumit Parkash Mar 19 '19 at 11:52
  • My backend is ASP .NET c#, how it will be? – Lechucico Mar 19 '19 at 11:54
  • don't idea about the .Net, but i can simplify what the above code does. Simply you need to get the callback variable in get request that you get in yours.Net file and return the json data wrap in that GET variable. 'echo $_GET['callback'] .'('. '{"key":"value"}'. ')';' that is you need to return something like this 'jQuery112005380381429956309_1552996718249({"key":"value"})' Replace jQuery112005380381429956309_1552996718249 with the value you get in callback get variable and the key value is the json object. – Sumit Parkash Mar 19 '19 at 12:00