jQuery cross-domain Ajax. Why is my code working?

My understanding is that if it is a cross-domain request, we are supposed to set dataType to “jsonp”. Which I did, but then it did not work. I got the following error message in the console:

Refused to execute script from ‘http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_p…_page]=1&callback=jQuery31105215916043980608_1487877164531&_=1487877164532’ because its MIME type (‘application/json’) is not executable, and strict MIME type checking is enabled.

But when I set it to “json”, it worked.
Can anyone explain why?

Here is my code:

$(“#btn-one-quote”).on(“click”, function(){
$.ajax({
url: “http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1”,
cache: false,
dataType: “json”,
success: function(quote){
$(“#one-quote-output”).html(quote[0].content);
}
});
});

There’s another, newer way of making cross-origin request: CORS. If a provider (server) supports it, a client can just send normal requests without any additional setup. That’s why your request succeeded.

If you want to use jsonp, you need to provide an additional parameter ( _jsonp) to your query string to inform the provider that’s the format you want to use (as you can read in api docs).

Thank you for your answer.

Could you please elaborate on this:

you need to provide an additional parameter ( _jsonp) to your query string

How do I do that? Is it a setting in $.ajax(); if so which one? I can’t seem to find that in the jQuery API (jQuery.ajax() | jQuery API Documentation).

Also, do I need to always do that, or only when the server supports CORS?

Best way to fetch the data:

$('#your-button').on('click', function(e) {
    e.preventDefault();
    $.ajax( {
      url: '/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1',
      success: yourCallback,
      cache: false
    });
  });
});

more about cors and jsonp

Thank you for your answer.

1 Like